views:

1000

answers:

1

I want to edit the user's username inside a UITableView. I added a UITextField to the UITableViewCell and this seems to work very nicely. But when the user touches the cell (even outside the textfield), he expects to edit.

How do I programatically select the textfield?

The code would look something like:

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
userName.selected = TRUE;
}
+2  A: 
- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
   UITableViewCell *cellSelected = [tableView cellForRowAtIndexPath: indexPath];
   UITextField *textField = [[cellSelected.contentView subviews] objectAtIndex: 0];
   [textField becomeFirstResponder];

   [tableView deselectRowAtIndexPath: indexPath animated: NO];

}

This assumes that you have no quicker way to know which UITextField object is in which cell, and that you know for sure that the UITextField will be the first subview.

You also might want to put in a check for [textField isFirstResponder] -- no point in making it the firstResponder if it already is. This may not be necessary though.

Amagrammer