我想在UITableView中编辑用户的用户名。我在UITableViewCell中添加了一个UITextField,这看起来效果非常好。但是当用户触摸单元格时(甚至在文本区域外),他希望编辑。

如何以编程方式选择文本字段?

代码看起来像:

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
userName.selected = TRUE;
}
有帮助吗?

解决方案

- (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];

}

这假设您没有更快的方法来知道哪个UITextField对象在哪个单元格中,并且您确定UITextField将是第一个子视图。

您也可能想要检查[textField isFirstResponder] - 如果它已经是第一个响应者,则没有任何意义。但这可能不是必要的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top