如何根据 ios swift 中的 uitableview 多选中的选定行数限制选择样式

how to restrict selection style based on selected row count in uitableview multiselct in ios swift

我在这里遇到了 tableview multiselect 的问题,任何人都可以帮助我。我想限制 table 查看 selection 具有一定的行数(对于列表中的前 5 行)。selected 行必须采用 selection 样式作为 .blue ,当我尝试 select 第 6 行时,那行 selection 样式应该是。none.but 我试过它但不知何故无法正常工作。

这是我的代码

tableview.allowsMultipleSelectionDuringEditing = true

cellForRowAtIndexPath方法中,

if SelectedArray.count <= 5
{
     cell.selectionStyle = UITableViewCellSelectionStyle.Blue
} 
else {
      cell.selectionStyle = UITableViewCellSelectionStyle.None
 }

并在 didSelectRowAtIndexPathwillDisplayCell 中定义了上述声明,并且在 didselectrow

时重新加载我的 table

这也尝试了 didSelectRowAtIndexPath 方法,

self.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath)

但是没有用,请帮帮我

提前致谢。

请试试这个

func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {

    if let sr = tableView.indexPathsForSelectedRows {
        if sr.count == limit {
            let alertController = UIAlertController(title: "Oops", message:
                "You are limited to \(limit) selections", preferredStyle: .Alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: {action in
            }))
            self.presentViewController(alertController, animated: true, completion: nil)

            return nil
        }
    }

    return indexPath
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    print("selected  \(intervalNames[indexPath.row])")

    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        if cell.selected {
            cell.accessoryType = .Checkmark
        }
    }

    if let sr = tableView.indexPathsForSelectedRows {
        print("didDeselectRowAtIndexPath selected rows:\(sr)")
    }
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

    print("deselected  \(intervalNames[indexPath.row])")

    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        cell.accessoryType = .None
    }

    if let sr = tableView.indexPathsForSelectedRows {
        print("didDeselectRowAtIndexPath selected rows:\(sr)")
    }
  }

}

欲了解更多详情,请访问此 link https://github.com/genedelisa/LimitTableExample