2015-01-15 65 views
0

如果用户取消选择一行,我试图删除数组中的某个项目selectedFoodTypes。不过,我一直运行到错误:取消选择单元格时从阵列中删除值

fatal error: unexpectedly found nil while unwrapping an Optional value

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 
    let indexPath = tableView.indexPathForSelectedRow(); 
    let deselectedCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell! 
    selectedFoodTypes = selectedFoodTypes.filter {$0 != deselectedCell.textLabel!.text!} 
    println(selectedFoodTypes) 
} 

enter image description here

回答

1

你为什么打电话let indexPath = tableView.indexPathForSelectedRow()

功能的indexPath参数为您提供了取消行的indexPath

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 
    let deselectedCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell! 
    selectedFoodTypes = selectedFoodTypes.filter {$0 != deselectedCell.textLabel!.text!} 
    println(selectedFoodTypes) 
} 

上面的代码可能工作。但与细胞的textLabel.text比较不是一个好主意。如果datasourceArray是例如一个数组,并设置为的tableView dataSource,你可以做

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 
    let deselectedCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell! 
    selectedFoodTypes = selectedFoodTypes.filter {$0 != datasourceArray[indexPath.row]} 
    println(selectedFoodTypes) 
} 
+0

的问题是我需要的数组包含每一行的字符串值。由于我允许多个选择,用户可能会按顺序选择行。因此,从indexPath.row转换为相应的字符串变得困难 – Onichan

+0

什么是tableview的'datasource'?也许它更好地做到这一点,就像我上面显示的那样。 – rakeshbs

+0

让我试试你的代码。它是一个UITableViewController – Onichan

相关问题