如何根据 iOS Swift 中的 UitableView Multiselct 中的选定行数限制选择样式



在这里,我在多选tableview遇到问题,谁能帮我。 我想限制具有一定行数的表视图选择(例如列表中的 5 行).选定的行必须采用 .blue 的选择样式,当我尝试选择第 6 行时,该行选择样式应该是 .none.但我尝试过以某种方式无法正常工作。

这是我的代码

tableview.allowsMultipleSelectionDuringEditing = true

cellForRowAtIndexPath方法中,

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

并在didSelectRowAtIndexPath中定义了上面的声明,willDisplayCell并在didselectrow时重新加载我的表,

这也尝试了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)")
    }
  }
}

有关更多详细信息,请访问此链接 https://github.com/genedelisa/LimitTableExample

最新更新