Checkmark on static cells uitableview

白昼怎懂夜的黑 提交于 2019-12-03 06:57:50

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.

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
            }
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!