【问题标题】:Checkmark on static cells uitableview静态单元格上的复选标记
【发布时间】:2016-11-29 04:08:29
【问题描述】:

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

  • 货币
  • 语言
  • 社交

它们有不同的行数:

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

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

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

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

【问题讨论】:

    标签: uitableview swift tableviewcell


    【解决方案1】:

    如果为响应点击单元格设置复选标记,只需执行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
            }
        }
    }
    

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

    【讨论】:

    • 看起来它会起作用,+1。如果每个部分只能有 1 个复选标记,那我应该怎么做呢?语言设置不能同时为 EN 和 JP。货币只能是美元、欧元或日元。
    • @Gino 我已经更新了第一个代码示例,只在给定部分中最后点击的单元格旁边放了一个复选标记。它只是枚举点击部分中的表格视图单元格,并确保只有点击的行有复选标记。
    • 哦,哇,我学到了很多在 O'Reilly Swift 书中找不到的新东西。非常感谢队友。 +1
    • 谢谢!为我工作,但我不知道这是否是更好的解决方案
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多