How to select a UITextField?

安稳与你 提交于 2019-12-04 11:52:45

问题


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;
}

回答1:


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



来源:https://stackoverflow.com/questions/1207102/how-to-select-a-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!