Question

I have a row that has an insertion accessory when my tableView is being edited, and it inserts a new table view cell above it that has a text field. How do I make the text field active (i.e. becomeFirstResponder) ? e.g. in the Apple Contacts app if you add a new phone, it automatically selects the text field for the new row and the keyboard appears.

From searching online it seems that the cell's textField is not instantly added to the queue, so you have to call becomeFirstResponder at the right time. When should I call it?

in commitEditingStyle: forRowAtIndexPath I tried: ...

else if (editingStyle == UITableViewCellEditingStyleInsert) {
    [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    MyCustomCell* cell = [tableView cellForRowAtIndexPath: indexPath];
    [cell.textField becomeFirstResponder];
}

Did not work.

In cellForRowAtIndexPath I also tried (bit of a hack):

if (cell.textField.text.length == 0) {
    [conditionCell.textField becomeFirstResponder];
}

But it didn't seem to respond there either. (become first responder returns FALSE)

Where is the right place to call becomeFirstResponder?

Thanks

EDIT: Actually the problem was because of the following line I have in cellForRowAtIndexPath:

cell.textField.enabled = NO;

I didn't want the textFields to be active unless the table was in editing mode, so I disable them and only re-enable them in didSelectCellAtIndexPath if the table is in editing mode.

Prime example of why you're supposed to post all your code, not just snippets of what you think is relevant.

Was it helpful?

Solution

In cellForIndexPath I disable the textfield, and I forgot to re-enable it before calling becomeFirstResponder.

There is no issue with the queue etc. Should work just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top