Reputation: 859
I need enable edit textfield when edit mode for UITableView enabled. It works fine:
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) ->
Bool {
if (self.tableView.editing)
{
let cell = tableView.cellForRowAtIndexPath(indexPath) as TestTableViewCell
cell.testTextField.enabled=true
cell.showsReorderControl = true
return true
}
else{
return false
}
}
When edit mode off, textfield steel editable. I add code to else for fix it:
else{
let cell2 = self.tableView.cellForRowAtIndexPath(indexPath) as TestTableViewCell
cell2.testTextField.enabled=false
return false
}
But I get error "fatal error: unexpectedly found nil while unwrapping an Optional value" on this line
let cell2 = self.tableView.cellForRowAtIndexPath(indexPath) as TestTableViewCell
Upvotes: 3
Views: 1103
Reputation: 239
From what error Xcode given, you need to check the data type.
else{
let cell2 = self.tableView.cellForRowAtIndexPath(indexPath) as? TestTableViewCell
cell2?.testTextField.enabled=false
return false
}
Add '?' after 'as' will have a condition check, and add another '?' to set attribute only when it is not nil.
This is a very common problem when programming with Optional value. Hope this can help.
Upvotes: 1
Reputation: 119031
cellForRowAtIndexPath
will only return a cell if it is actually loaded, i.e. actually visible. Any rows that aren't visible don't have loaded cells.
So, you should check visibility and check the editing status in the cell creation / appearance / disappearance delegate methods so that you can set the appropriate state onto the cells.
Upvotes: 3