sysuser
sysuser

Reputation: 1100

UITableViewCellAccessoryType.Checkmark shows checkmark only when another row is tapped

I have the following code

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    cell.textLabel?.text = users[indexPath.row]
    return cell
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    var cell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
    cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}

The purpose was to show a checkmark when a row is tapped. Have two rows and I am observing the following behavior.

  1. Tap row 0, can't see the checkmark
  2. Tap row 1, can see the checkmark for the row 0
  3. Tap row 0, can now see the checkmark for row 1

The selection attribute settings are (Xcode default)

Selection: Single Selection Editing: No selection during editing

Is there anything I should do to show the checkmark when the row is tapped in addition to the above code. Looked into related questions but couldn't nail it.

Upvotes: 0

Views: 692

Answers (1)

ZeMoon
ZeMoon

Reputation: 20284

This is a very common problem, I think almost everybody who does iOS programming has faced the same.

You need to change

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath)

to

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

The issue is with the XCode suggestions as one types the UITableView delegate methods. Since deselect comes first alphabetically, it is a very common mistake. I used to face this issue with Objective C, it's funny to see this problem arising with Swift as well.

Upvotes: 2

Related Questions