Kiwo Tew
Kiwo Tew

Reputation: 1531

swift table view adding custom checkmark to cell and remove checkmark from previous cell

I have a Image view in my cell which displays a checkmark icon.

What I want to do is when you touch a cell the checkmark should appear. I got this working, but my problem now is that I can't remove the checkmark from the previous selected cell. - only one cell should be able to be selected.

I've tried to get this working in didSelectRowAtIndexPath but I can't get it right so I am stuck right now.

Update:

var selectedRow: NSIndexPath?

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: searchCityTableViewCell!

        if (indexPath.section == 0) {
            cell = tableView.dequeueReusableCellWithIdentifier("staticCityCell") as! searchCityTableViewCell
            cell.titleLabel?.text = "Within \(stateName)"                
        }else if (indexPath.section == 1) {
            cell = tableView.dequeueReusableCellWithIdentifier("cityCell") as! searchCityTableViewCell
            let state = cities[indexPath.row]
            cell.configureWithStates(state)
            if indexPath == selectedRow {
                cell.cityImage.select()
            } else {
                cell.cityImage.deselect()
            }
        }

        return cell

    }

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let paths:[NSIndexPath]

        if let previous = selectedRow {
            paths = [indexPath, previous]
        } else {
            paths = [indexPath]
        }
        selectedRow = indexPath
        tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .None)
    }

Upvotes: 0

Views: 2241

Answers (1)

vacawama
vacawama

Reputation: 154721

  1. Keep track of which row is currently selected. Add a property to your ViewController:

    var selectedRow: NSIndexPath?
    
  2. In didSelectRowAtIndexPath:

    let paths:[NSIndexPath]
    
    if let previous = selectedRow {
        paths = [indexPath, previous]
    } else {
        paths = [indexPath]
    }
    selectedRow = indexPath
    tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .None)
    
  3. In cellForRowAtIndexPath:

    if indexPath == selectedRow {
        // set checkmark image
    } else {
        // set no image
    }
    

An important thing to note is that the state of which row is selected should be stored in the model and not in the cell. The table should reflect the state of the model. In this case, the model can simply be the indexPath of the selected row. Once the model is updated (selectedRow is set), the affected rows should reload their state.

Upvotes: 4

Related Questions