取消选择单元格时从数组中删除值

Removing Value from Array when Deselect Cell

如果用户取消选择某行,我将尝试删除数组 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 {[=10=] != deselectedCell.textLabel!.text!}
    println(selectedFoodTypes)
}

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

函数的 indexPath 参数为您提供取消选择的行的 indexPath

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

以上代码可能有效。但是与单元格的 textLabel.text 进行比较并不是一个好主意。例如datasourceArray是一个数组,设置为tableViewdataSource,你可以

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