TableView CheckMark and Uncheck With Scroll Up Still Checked Cell Value In Ios Swift 4

后端 未结 2 1350
野的像风
野的像风 2020-12-12 01:22

TableView CheckMark Cell Value Removed After Scrolling Up It will Fix TableView in You have face a problem many times to Checkmark after scroll Up then Scro

2条回答
  •  不思量自难忘°
    2020-12-12 01:51

    You are strongly discouraged from using a second array to keep the selected state.

    This is Swift, an object oriented language. Use a custom struct for both num and the selected state.
    In didSelectRowAt and didDeselectRowAt change the value of isSelected and reload the row.

    And use always the dequeueReusableCell API which returns a non-optional cell.

    struct Item {
       let num : Int
       var isSelected : Bool
    }
    
    var numarr = [Item]()
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return numarr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "id", for: indexPath)
        let item = numarr[indexPath.row]
        cell.textLabel?.text = String(item)
        cell.accessoryType = item.isSelected ? .checkmark : .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        updateSelection(at: indexPath, value : true)
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        updateSelection(at: indexPath, value : false)
    }
    
    func updateSelection(at indexPath: IndexPath, value : Bool) {
        let item = numarr[indexPath.row]
        item.isSelected = value
        tableView.reloadRows(at: [indexPath], with: .none)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        (0...100).map{Item(num: $0, isSelected: false)}
    }
    

提交回复
热议问题