勾选静态单元格uitableview

Gin*_*ino 8 uitableview tableviewcell swift

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

  • 货币
  • 语言
  • 社会

它们具有不同的行数:

  • 货币有3行(美元,欧元,日元)
  • 语言有2行(EN,JP)
  • 社交有3行(Twitter,FB,Line)

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

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

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

Stu*_*art 13

如果设置了复选标记以响应单击单元格,只需执行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 ...
}
Run Code Online (Sandbox Code Playgroud)

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

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不需要为每个部分/单元格创建单独的子类.


hdo*_*ria 5

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
            }
        }
}
Run Code Online (Sandbox Code Playgroud)