Gino
Gino

Reputation: 951

Checkmark on static cells uitableview

I'm using a UITableView, with 3 sections ( Static Cells )

They have different number of rows:

Right now, I have by default set a checkmark at the first row of every section. However, I would like to allow the user to set their default settings and change the checkmark accordingly based on what they have set.

My question is then how do I set the checkmark for 3 different sections each with varying number of rows?

Do I need to set an cell identifier for each Section? Do I also need to create a UITableViewCell swift file for each Section?

Upvotes: 9

Views: 3458

Answers (2)

hdoria
hdoria

Reputation: 644

Just a quick update for Swift 3:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = indexPath.section
        let numberOfRows = tableView.numberOfRows(inSection: section)
        for row in 0..<numberOfRows {
            if let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) {
                cell.accessoryType = row == indexPath.row ? .checkmark : .none
            }
        }
}

Upvotes: 6

Stuart
Stuart

Reputation: 37053

If the checkmarks are set in response to tapping on the cell, just implement tableView(_:didSelectRowAtIndexPath:):

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let section = indexPath.section
    let numberOfRows = tableView.numberOfRowsInSection(section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
            cell.accessoryType = row == indexPath.row ? .Checkmark : .None
        }
    }
    // ... update the model ...
}

Otherwise, you can set identifiers for each cell in your storyboard (or outlets if you prefer, since the cells aren't reused), and then just set the checkmark programmatically. For example, using a delegate method:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if let identifier = cell.reuseIdentifier {
        switch identifier {
            "USD Cell": cell.accessoryType = model.usdChecked ? .Checkmark : .None
            "EUR Cell": cell.accessoryType = model.eurChecked ? .Checkmark : .None
            //...
            default: break
        }
    }
}

There shouldn't be a need to create a separate subclass for each section/cell.

Upvotes: 14

Related Questions