Mc.Lover Mc.Lover - 4 months ago 32
Swift Question

Get string from some textfield in a custom UITableViewCell

I have a table view with 5 cells each cell has its own identifier I am trying to get and

print
strings from each UITextFields, I have some labels as well. Here is my code :

let index: NSIndexPath = NSIndexPath(forRow:0 , inSection: 0)
let cell: CustomCell = tableView.cellForRowAtIndexPath(index) as! CustomCell
print(cell.title.text!)


it works fine until I set row value dynamically, for example if textfield from cell 0 is selected print
cell.title.text
if textfield string is from cell 1 print its value. so I add this line of code :

let IndexPath:NSIndexPath = tableView.indexPathForSelectedRow!
switch IndexPath.row {
case 0:
row = 0

case 1:
row = 1

default:
break
}


let index: NSIndexPath = NSIndexPath(forRow:row /***CHANGED VALUE***/ , inSection: 0)
let cell: CustomCell = tableView.cellForRowAtIndexPath(index) as! CustomCell
print(cell.title.text!)


app crashes at this line :

let IndexPath:NSIndexPath = tableView.indexPathForSelectedRow!


due to
fatal error: unexpectedly found nil while unwrapping an Optional value
. Any help would be great !

Hoa Hoa
Answer

indexPathForSelectedRow can return a nilwhen you did not select any row. So you have to check if it exists before any unwrappring operation.

if let IndexPath:NSIndexPath = tableView.indexPathForSelectedRow {
    //do your work
}
Comments