我不知道 didSelectRowAt 方法如何更改数组中的所有元素(在每个索引处) 那里有打印语句来可视化结果,因此在单击单元格 1 两次后我得到: 1个 真真真 1个 假假假
不知道 indexPath.row 是如何变得疯狂并遍历整个数组范围的 任何帮助将不胜感激
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath)
cell.textLabel?.text = itemArray[indexPath.row].title
if itemArray[indexPath.row].done == true {
cell.accessoryType = .checkmark
}else{
cell.accessoryType = .none
}
return cell
}
//MARK: TableView Delegate methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
if itemArray[indexPath.row].done == true {
itemArray[indexPath.row].done = false
print(itemArray[indexPath.row].done, itemArray[indexPath.row-1].done, itemArray[indexPath.row+1].done)
}else{
itemArray[indexPath.row].done = true
print(itemArray[indexPath.row].done, itemArray[indexPath.row-1].done, itemArray[indexPath.row+1].done)
}
tableView.reloadData()
tableView.deselectRow(at: indexPath, animated: true)
}
项目类型是:
class Item {
var title : String = ""
var done : Bool = false
}
数组是这样填充的:
override func viewDidLoad() {
super.viewDidLoad()
let newItem: Item = Item()
newItem.title = "asdaS"
itemArray.append(newItem)
itemArray.append(newItem)
itemArray.append(newItem)
}
最佳答案
您只是创建一个对象并将同一对象追加到数组中。当您更改任何索引时,它会更新整个数组,因为所有索引都包含某个对象
class Item {
var name = ""
var done = true
}
let x = Item()
var arr = [Item]()
for _ in 0..<5 {
arr.append(x)
}
print(arr.flatMap({ $0.done })) //[true, true, true, true, true]
arr[1].done = false
print(arr.flatMap({ $0.done })) //[false, false, false, false, false]
您需要做的是为每个索引创建一个单独的对象
class Item {
var name = ""
var done = true
}
var arr = [Item]()
for _ in 0..<5 {
let x = Item() //NOTICE THAT THIS LINE HAS BEEN MOVED INSIDE THE LOOP
arr.append(x)
}
print(arr.flatMap({ $0.done })) //[true, true, true, true, true]
arr[1].done = false
print(arr.flatMap({ $0.done })) //[true, false, true, true, true]
关于arrays - didSelectRowAt 更改所有行中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51492668/