Gino Gino - 1 year ago 131
Swift Question

Checkmark on static cells uitableview

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

  • Currency

  • Language

  • Social

They have different number of rows:

  • Currency has 3 rows ( USD, EUR, JPY )

  • Language has 2 rows ( EN, JP )

  • Social has 3 rows ( Twitter, FB, Line )

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download