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.
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 theFriend
reference from there selected index.let selectedFriend = self.allFriends[indexPath.row]
Then you can keep your logic simple.
Your image logic should then simply go inside you
cellForRowAtIndexPath
method.