UITableView - 多选和单选

时间:2015-09-30 03:06:45

标签: swift uitableview xcode7

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

enter image description here

4 个答案:

答案 0 :(得分:6)

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

夫特-4

csv.reader()

答案 1 :(得分:4)

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

tableView(_:shouldHighlightRowAtIndexPath:)

tableView(_:didSelectRowAtIndexPath:)

...并确定(来自indexPath.rowindexPath.section)相关部分是否支持单/多选(这取决于您的数据模型的自定义逻辑-eg:&# 34;部分0支持多选,但部分1不支持#34;),如果它只支持单选,请检查是否已选择行(通过访问tableView.indexPathsForSelectedRows) 。

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

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

答案 2 :(得分:2)

这很容易通过两行来实现,如下所示:(快速4)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if sectionAllowsMultipleSelection {
        if let indexPathsInSection = tableView.indexPathsForSelectedRows?.filter ({ $0.section == indexPath.section && $0.row != indexPath.row }) {
            for selectedPath in indexPathsInSection {
                tableView.deselectRow(at: selectedPath, animated: false)
            }
        }
    }
}

答案 3 :(得分:0)

如果您希望第2部分中的选定行成为新选定的行,则这可能对您有用。另外,请使用@ NicolasMiari的回答。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 1 {
        for i in 0..tableView.numberOfRowsInSection(indexPath.section) - 1 {
            let cell: UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: i, inSection: indexPath.section))!
            if (i == indexPath.row) {
                cell.accessoryType = .Checkmark
                cell.selected = false
            }
            else {
                cell.accessoryType = .None
            }
        }
    }
    else {
        //Do whatever for the first section
    }
}

不是很优雅,但希望它会给你一个想法。