Selecting Multiple Table View Cells At Once in Swift

128 Views Asked by At

I am trying to make an add friends list where the user selects multiple table view cells and a custom check appears for each selection. I originally used didSelectRowAtIndexPath, but this did not give me the results I am looking for since you can highlight multiple cells, but unless you unhighlight the original selected row you cannot select anymore. I then tried using didHighlighRowAtIndexPath, but this doesn't seem to work because now I am getting a nil value for my indexPath. Here is my code:

override func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {

    let indexPath = tableView.indexPathForSelectedRow

    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! AddedYouCell

    let currentUser = PFUser.currentUser()?.username

    let username = currentCell.Username.text
    print(currentCell.Username.text)

    let Friends = PFObject(className: "Friends");

    Friends.setObject(username!, forKey: "To");
    Friends.setObject(currentUser!, forKey: "From");

    Friends.saveInBackgroundWithBlock { (success: Bool,error: NSError?) -> Void in

        print("Friend has been added.");


        currentCell.Added.image = UIImage(named: "checked.png")

    }



}

How can I solve this? Thanks

1

There are 1 best solutions below

2
On BEST ANSWER

I'm not going to write the code for you, but this should help you on your way:

To achieve your goal, you should separate the data from your views (cells). Use an Array (i.e. friendList) to store your friend list and selected state of each of them, and use that Array to populate your tableView.

numberOfCellsForRow equals friendList.count

In didSelectRowAtIndexPath, use indexPath.row to change the state of your view (cell) and set the state for the same index in your Array

In cellForRowAtIndexpath, use indexPath.row to retrieve from the Array what the initial state of the cell should be.