2015-01-15 63 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

相關問題