UITableView checkmarks duplicated

半世苍凉 提交于 2019-12-08 16:30:30

Your problem is not inside this method but in the one that "loads" the cells. (cell for row)

Since Table Views use reusable cells, more often than not they will be loading a cell that was already presented somewhere else.

Because of this, on the cell loading method you should "Reset the state" the loaded cell, this includes the accessory type, and any other properties you might have changed.

So just change this in your code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
    myCell.selectionStyle = UITableViewCellSelectionStyle.none
    myCell.nameLabel.text = userList[indexPath.row].name

    // ADD THIS
    if userList[indexPath.row].isSelected {
        myCell.accessoryType = UITableViewCellAccessoryType.checkmark
    } else {
        myCell.accessoryType = UITableViewCellAccessoryType.none
    }

    return myCell
}

EDIT:

"userList[indexPath.row].isSelected" is a property that YOU have to create and manage. (So you must also modify it in the didSelectRowAt method.

The issue is you are not maintaining the selected User info properly, which will be used while you scroll the table and when the cell has to reload data.

As you have already created var selected = [String]() , I suggest using the same.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
    let dataFoundInselectedArr =  selected.filter { $0 == userList[indexPath.row].name}

    if(dataFoundInselectedArr.count > 0){
          myCell.accessoryType = UITableViewCellSelectionStyle.checkmark
    }else{
          myCell.accessoryType = UITableViewCellSelectionStyle.none
    }

    myCell.nameLabel.text = userList[indexPath.row].name
    return myCell
}

The table selection delegate method remains the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!