didSelectRowAt更改所有行中的值

时间:2018-07-24 07:17:12

标签: arrays swift uitableview

我不知道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)

}

1 个答案:

答案 0 :(得分:2)

您仅创建一个对象并将同一对象附加到数组中。当您更改任何索引时,它会更新整个数组,因为所有索引都包含某个对象

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]