Table View Cell Selection Error

50 views Asked by At

I have a table view where the user selects friends. My problem is that for some reason when one cell gets selected another unrelated cell gets selected as well. Can anyone help me understand what is happening?

Here is my code for handling the selections:

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     let indexPath = tableView.indexPathForSelectedRow
     let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! SpotFriendsCell
     let Friend = currentCell.AddFriendLabel.text
     if self.invitedFriends.containsObject(Friend!) {
         invitedFriends.removeObject(Friend!)
         currentCell.Invited.image = UIImage(named: "unckecked.png")
         tableView.reloadData()
     } else {
         invitedFriends.addObject(Friend!)
         NSUserDefaults.standardUserDefaults().setObject("Yes", forKey: "selectedFriends")
         currentCell.Invited.image = UIImage(named: "checked.png")
         tableView.reloadData()
     }
}

I have a UIImageView on the right of the cell that I use to keep track of what friends are selected and are not. If the cell image is "unchecked.png" then the friend is added and the image is changed to "checked.png". and vice versa.

2

There are 2 answers

2
Marc-Alexandre Bérubé On BEST ANSWER

This line shouldn't be needed as you already have the indexPath in the parameter.

let indexPath = tableView.indexPathForSelectedRow

Then, instead of playing with cells directly, you should play with objects. My guess is that you already have a list containing Friend somewhere, you should get the Friend reference from there selected index.

let selectedFriend = self.allFriends[indexPath.row]

Then you can keep your logic simple.

if self.invitedFriends.containsObject(selectedFriend) {
     invitedFriends.removeObject(selectedFriend)
     } else {
         invitedFriends.addObject(selectedFriend)
         NSUserDefaults.standardUserDefaults().setObject("Yes", forKey: "selectedFriends")
     }

    tableView.reloadData()
}

Your image logic should then simply go inside you cellForRowAtIndexPath method.

3
Martijn On

When you reloadData, your cells are regenerated from the prototype cell to reuse. If you don't add the functionality to set this image according to your datasource in cellForRowAtIndexPath, the image will always default to the one in your prototype cell.