slider
slider

Reputation: 2816

TableViewCell scroll selects wrong cells when scrolling

My tableview highlights the wrong cells when I scroll up and down. In didSelectRowAtIndexPath, I'm trying to add the .Checkmark accessory view as well as change the font of cell.textLabel?.text. Upon scrolling, random rows are selected and the ones I manually select sometimes deselect.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as! MyCell

        cell.textLabel?.text = self.array[indexPath.row]

        return cell

    }


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!

        if cell.accessoryType == UITableViewCellAccessoryType.Checkmark {

            cell.accessoryType = .None

            cell.textLabel!.font = UIFont(name: "HelveticaNeue", size: 16)
tableView.deselectRowAtIndexPath(indexPath, animated: true)

        } else if cell.accessoryType == UITableViewCellAccessoryType.None {

            cell.accessoryType = .Checkmark

            cell.textLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: 16)
        }

            tableView.deselectRowAtIndexPath(indexPath, animated: true)

}

Upvotes: 1

Views: 1306

Answers (1)

Andriy Gordiychuk
Andriy Gordiychuk

Reputation: 6272

Declare array which will keep track of which rows are selected:

var selectedRows:[Bool] = []

You need to make sure that it is populated with the same number of items as your data array.

Then modify your cellForRowAtIndexPath:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as! MyCell

    cell.textLabel?.text = self.array[indexPath.row]
        if selectedRows[indexPath.row] {
            // row selected
            cell.accessoryType = .Checkmark
        }
        else {
            cell.accessoryType = .None
        }

    return cell

}

And in your didSelectRow function add line:

selectedRows[indexPath.row] = !selectedRows[indexPath.row]

When you modify your cell from didSelectRow the next time cell is dequeued it will have the accessory type which you set. The reason why it happens after scroll is because when you scroll the cells which become visible get dequeued. So, you need to manually set correct accessory type for them

Upvotes: 3

Related Questions