静态单元格 uitableview 上的复选标记

Checkmark on static cells uitableview

我使用的是 UITableView,有 3 个部分(静态单元格)

它们的行数不同:

现在,我默认在每个部分的第一行设置了一个复选标记。但是,我想允许用户设置他们的默认设置并根据他们的设置相应地更改复选标记。

我的问题是如何为 3 个不同的部分设置复选标记,每个部分的行数不同?

是否需要为每个 Section 设置单元格标识符?我还需要为每个部分创建一个 UITableViewCell swift 文件吗?

如果设置复选标记以响应点击单元格,只需实施 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 ...
}

否则,您可以为故事板中的每个单元格设置标识符(如果您愿意,也可以设置插座,因为单元格不会被重复使用),然后只需以编程方式设置复选标记。例如,使用委托方法:

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
        }
    }
}

不需要为每个 section/cell 创建一个单独的子类。

Swift3 的快速更新:

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
            }
        }
}