【发布时间】:2019-03-29 07:01:23
【问题描述】:
我有一个数组,我首先将它加载到 tableview 单元格中,然后在单击单元格时,该值会附加到数组中,并将数组中所有元素的总和打印到 UILabel。
当数组有不同的元素时这很好用,但是当有相同的元素时它会失败。
这是我的代码。
let amount:[String] = ["1","1","1"]
var amountsSelected:[String] = []
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Check if it is not in the array
if(!amountsSelected.contains(amount[indexPath.row])){
amountsSelected.append(amount[indexPath.row])
let intArray = amountsSelected.map { Int($0)!}
let total = intArray.reduce(0, +)
moneyText.text = String(total)
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
}else if(amountsSelected.contains(amount[indexPath.row])){
//check if it is present in the array
amountsSelected.append(amount[indexPath.row])
let intArray = amountsSelected.map { Int($0)!}
let total = intArray.reduce(0, +)
moneyText.text = String(total)
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
}else{
//just remove
amountsSelected = amountsSelected.filter({$0 != amount[indexPath.row]})
print(amountsSelected)
let intArray = amountsSelected.map { Int($0)!}
let total = intArray.reduce(0, +)
moneyText.text = String(total)
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
}
}
}
即使在取消选择 UILabel 的值后尝试这个,它也会不断增加而不是减少。 任何帮助将不胜感激
【问题讨论】:
-
请指出 if 和 else-if 子句的区别。也许我错过了一些东西,但对我来说它们看起来一样。另外,你有没有设法进入最后一个 else 子句,对我来说似乎是不可能的。
-
首先,如果我比较 if(!amountsSelected.contains(amount[indexPath.row])) //即,我检查它是否不存在于数组中。在 elseif 我做 else if(amountsSelected.contains(amount[indexPath.row])) //检查它们是否相同。在 else 我做 amountSelected = amountSelected.filter({$0 != amount[indexPath.row]} ) 只是删除
-
好的,我们来解决一些问题:首先,if 和 else-if-clause 中的代码是相同的。因此,无论条件如何,都会发生同样的事情。其次,不能调用 else 子句(正如 Daniel 指出的那样)。第三,您刚刚发布了 didSelect 方法,因此取消选择它时不会发生任何事情(因为您似乎预计会减少)。