我有一个表格视图,其中带有价格的食品杂货选项存储在字典中。
一旦用户从表格视图中选择一行,商品名称和价格就会添加到词典中并在控制台中打印。
问题是我也试图在标签中显示商品名称和价格,以供用户查看,但我似乎无法正常工作,因为每次用户单击新行时,当我迭代商品中的数据时,标签覆盖而不是追加到新行。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var items : Dictionary<Int, String> = [:]
@IBOutlet weak var groceryTable: UITableView!{
didSet {
groceryTable.dataSource = self
}
}
var groceryData:Dictionary<String, String> = ["Apple":"1", "Kiwi":"2", "Mango":"4", "Broccoli":"3","Milk":"4", "Eggs":"3", "Bread":"6"]
@IBOutlet weak var label: UILabel!
//selection of row handler
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Item added!")
let currentCell = tableView.cellForRow(at: indexPath) as! UITableViewCell
let val = currentCell.textLabel!.text
items.updateValue(val!, forKey: indexPath.row)
print(items)
for data in items{
let value = data.value
let line = "\n"
var a = ""
a.append(value + line)
self.label.text=a
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
print("Item removed!")
items.removeValue(forKey: indexPath.row)
print(items)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groceryData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let key = Array(self.groceryData.keys)[indexPath.row]
let value = Array(self.groceryData.values)[indexPath.row]
cell.textLabel?.text = key + ", $"+value
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
实际结果是,每点击一次新行,标签就会被覆盖: 鸡蛋,3美元
预期: 芒果,4美元 面包,6美元 鸡蛋,3美元
答案 0 :(得分:3)
您需要
self.label.text = self.label.text! + items.map { $0.value }.joined(separator:"\n")
答案 1 :(得分:0)
最终得到答案!
for data in items{
let value = data.value
label.text = label.text! + value + "\n"
items.removeValue(forKey: data.key)
}