Ios 如何统计Swift中选定的UITableView行。indexPathForSelectedRow中的可选项
我正在尝试获取我的tableView中选定的行数:Ios 如何统计Swift中选定的UITableView行。indexPathForSelectedRow中的可选项,ios,iphone,xcode,uitableview,swift,Ios,Iphone,Xcode,Uitableview,Swift,我正在尝试获取我的tableView中选定的行数: self.tableView.setEditing(true, animated: true) tableView.allowsMultipleSelection = true func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { updateCount() } func 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)
在选定某个对象之前,一切都很顺利。但当并没有选定的行时,应用程序会崩溃,并出现“致命错误:在展开可选值时意外发现零”。
我认为这是因为selection是nil,但是如何用Optionals编写代码呢?我试过了
很多方面,但当我取消选中所有选择时,应用程序仍然崩溃 是的,你在正确的轨道上。由于未选择任何行,因此发生错误。使用条件绑定,如下所示:
func updateCount(){
if let list = tableView.indexPathsForSelectedRows() as? [NSIndexPath] {
println(list.count)
}
}
你可以简单地做
func updateCount(){
if let list = tableView.indexPathsForSelectedRows {
print(list.count)
}
}
但是为什么需要这样做呢?例如,我可以有一个按钮“Delete”,显示要删除的项目数。FYI no()在indexpathsforselectedrows之后小心,如果列表为空,则不会调用该块。