-1

When I scroll the screen, the upper markings disappear. I've tried some solutions found here, but none worked ...

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    cell.textLabel?.text = players[indexPath.row]
    cell.textLabel?.textColor = UIColor.white
    cell.backgroundColor = colorForIndex(index: indexPath.row)
    cell.textLabel?.font = UIFont(name: "Chalkboard SE", size: 20)

    return cell
}

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.tableView.deselectRow(at: indexPath, animated: true)
    if let cell = tableView.cellForRow(at: indexPath){
        if (cell.accessoryType == .none) {
            cell.accessoryType = .checkmark
            let player = players[indexPath.row]
            playersSelecteds.append(player)
        } else {
            cell.accessoryType = .none
            let player = players[indexPath.row]
            if let position = playersSelecteds.index(of: player) {
                playersSelecteds.remove(at: position)
            }
        }
    }
}

1 Answers1

0

You should have a model for check-marked cells. because every time you scroll, the cells being reload based on your tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell method. So, for example add a model like this:

var playersCheckmarked: [Bool] = []

Then add in viewDidLoad some boolean to this array as many as players array have objects. Next in override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) method set playersCheckmarked[indexPath.row] = true or playersCheckmarked[indexPath.row] = false based on user selection. And of course in override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell method add this line:

cell.accessoryType = playersCheckmarked[indexPath.row] == true .checkmark : .none