UITableView - 多选和单选

use*_*523 9 uitableview swift xcode7

我的UITableView中有2个部分.
我希望第一部分允许多个单元格选择,第二部分只允许单个选择.
我尝试了一些代码,但效果不佳.
尽可能快速编码.谢谢.

在此输入图像描述

Ash*_*kad 6

你可以试试这个.这个解决方案非常适合我.试一试也许为别人工作......

斯威夫特-4

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.section == 0 {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.accessoryType = .checkmark
        }
    }
    else {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.accessoryType = .checkmark
        }
    }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if indexPath.section == 1 {
        if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
            cell.accessoryType = .none
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*ari 4

也许您可以实现表视图的委托方法:

tableView(_:shouldHighlightRowAtIndexPath:)

tableView(_:didSelectRowAtIndexPath:)

...并确定(从indexPath.rowindexPath.section)相关部分是否支持单项/多项选择(这将取决于您的数据模型的自定义逻辑 - 例如:“部分0支持多项选择,但部分1不支持”),以及是否仅支持单项选择,检查是否已经选择了一行(通过访问tableView.indexPathsForSelectedRows)。

如果已经有选定的行,您可以:

  1. 返回 falsetableView(_:shouldHighlightRowAtIndexPath:)
  2. 不执行任何操作(仅returntableView(_:didSelectRowAtIndexPath:)(我不确定当您false从返回时是否实际调用此方法shouldHighlight...,因此也许检查一下)。