所以我有一个 UITableView
,其中所有单元格都有一个 UITextField
作为带有 tag=1
的 subview 。令我困扰的是,我希望当用户单击文本字段并编辑它时知道发生在哪一行。我认为可以解决这个问题的是,当选择 subview (UITextField
)时,使单元格选择自身。我怎样才能实现这一目标?
我尝试使用数组,但由于单元格被重复使用,所以它不起作用。循环遍历所有行实在是太慢了。
最佳答案
默认情况下禁用每个单元格中的 UITextField
并使用 UITableView
委托(delegate)方法 didSelectRowAtIndexPath:
- 将所选行的索引路径存储在属性中
- 启用
UITextField
- 成为
UITextField
第一响应者
在类扩展中定义属性:
@interface MyTableViewController ()
@property (strong, nonatomic) NSIndexPath *activeIndex;
@end
在 didSelectRowAtIndexPath:
的实现中:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.activeIndex = indexPath;
AddCell *selectedCell = (AddCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[selectedCell.textField setEnabled:YES];
[selectedCell.textField becomeFirstResponder];
}
当 UITextField
放弃其第一响应者状态时,您需要再次禁用它。
假设您的 UITableViewController
是每个 UITextField
的委托(delegate),您可以在 UITextFieldDelegate
方法的实现中执行此操作:
-(void)textFieldDidEndEditing:(UITextField *)textField
{
[textField setEnabled:NO];
}
关于iOS 当一个人选择其中的 UITextField 时如何选择行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17523176/