Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a UITextField?

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;
}
like image 572
BankStrong Avatar asked Jul 30 '09 14:07

BankStrong


1 Answers

- (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.

like image 196
Amagrammer Avatar answered Sep 23 '22 16:09

Amagrammer