简体   繁体   English

如何计算Swift中选定的UITableView行。 indexPathForSelectedRow中的可选项

[英]How to count selected UITableView rows in Swift. Optional in indexPathForSelectedRow

I'm trying to get number of selected rows in my tableView: 我正在尝试获取tableView中所选行的数量:

self.tableView.setEditing(true, animated: true)

tableView.allowsMultipleSelection = true

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

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

func updateCount(){

  let list = tableView.indexPathsForSelectedRows() as [NSIndexPath]

  println(list.count)

Everything works good until something is selected. 一切都很好,直到选择了一些东西。 But when there is no selected row, app crashes with "fatal error: unexpectedly found nil while unwrapping an Optional value". 但是当没有选定的行时,应用程序崩溃并出现“致命错误:在展开Optional值时意外发现nil”。 I think it is because selection is nil, but how to write this code with Optionals? 我认为这是因为选择是零,但如何使用Optionals编写此代码? I tried many ways but app still crashes when I uncheck all selection. 我尝试了很多方法,但是当我取消选中所有选项时,app仍会崩溃。

Yes, you're on the right track. 是的,你走在正确的轨道上。 The error is happening because no rows are selected. 发生错误是因为没有选择任何行。 Use conditional binding like so: 像这样使用条件绑定:

func updateCount(){        
    if let list = tableView.indexPathsForSelectedRows() as? [NSIndexPath] {
        println(list.count)
    }
}

You can simply do 你可以干脆做

func updateCount(){
   if let list = tableView.indexPathsForSelectedRows {
        print(list.count)
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM