iPhone:跳转到uitableview中的下一个uitextfield,如何?
问题描述:
在我的iPhone项目中,我正在使用包含UITextfields的UITableViewCells的UITableview。我曾在许多应用程序中看到可以使用下一个按钮跳转到下一个单元格中的下一个文本字段。什么是完成这个最好的方法?iPhone:跳转到uitableview中的下一个uitextfield,如何?
我的想法是获取正在编辑的文本字段的单元格的indexPath,然后通过cellForRowAtIndexPath获取下一个单元格。但是我怎么能得到我目前正在编辑的单元格的indexPath?
谢谢!
答
- 请在表格视图中保留对
UITextField
实例的引用。 - 将唯一标记值分配给
UITextField
实例。 - 在你的最后文本字段,您可以设置它的返回键的类型,从“下一步”,“完成”改变键盘的回车键标签:
[finalTextField setReturnKeyType:UIReturnKeyDone];
在UITextField
委托方法-textFieldShouldReturn:
,通过走应答者:
- (BOOL) textFieldShouldReturn:(UITextField *)tf {
switch (tf.tag) {
case firstTextFieldTag:
[secondTextField becomeFirstResponder];
break;
case secondTextFieldTag:
[thirdTextField becomeFirstResponder];
break;
// etc.
default:
[tf resignFirstResponder];
break;
}
return YES;
}
答
假设的UITextField加入到的UITableViewCell像下面
UITableViewCell *cell;
UITextField *textField;
...
textField.tag = kTAG_TEXTFIELD;
[cell.contentView addSubview:textField];
...
您可以通过
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
if([textField.superView.superView isKindOfClass:[UITableViewCell class]]) {
UITableViewCell *cell = (UITableViewCell *)textField.superView.superView;
NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
}
...
获取当前索引路径然后下一行的的UITextField将
NSIndexPath *indexPathNextRow = [NSIndexPath indexPathForRow:(indexPath.row+1) inSection:indexPath.section];
UITableViewCell *cellNextRow = (UITableViewCell *)[self.myTableView cellForRowAtIndexPath:indexPathNextRow];
UITextField *textFieldNextRow = (UITextField *)[cellNextRow.contentView viewWithTag:kTAG_TEXTFIELD];
希望它能帮助!
+0
在iOS7中,您需要将textField.superView.superView替换为textField.superView.superView.superView – Homam 2014-03-31 06:31:11
谢谢!但我只是跟踪当前的文本框,因为有很多文本框。我能以某种方式获得下一个文本字段而不使用标签吗? – Mrbiggerm 2010-05-13 09:14:18
当然,只要保留对它们的引用,“UITextField * firstTextField”或使用数组等等。但标记可能是识别委托文本字段的最快方法。 – 2010-05-13 09:19:13
但是,如果我不想跟踪所有文本框或标签?我能否以某种方式获取当前正在编辑的文本字段所在的当前单元格,然后获取indexpath? – Mrbiggerm 2010-05-13 10:13:15