这本质上是@wain 答案的重复,但我想我会添加一些代码。
您可以保留对拥有活动文本字段的单元格的索引路径的引用(作为属性)。
然后,在 cellForRowAtIndexPath: 中是这样的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//I would hold a reference to the text field as a property on a subclass of UITableViewCell so that you can check for whether it exists.
if (!cell.textField) {
cell.textField = [[UITextField alloc] initWithFrame:cell.contentView.frame];
[cell.contentView addSubview:cell.textField];
}
return cell;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
UITableViewCell *cell = (UITableViewCell *)textField.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
self.indexPathForActiveTextField = indexPath;
}
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
MyTableViewCell *cell = (MyTableViewCell *)textField.superview.superview;
NSIndexPath *ip = [self.tableView indexPathForCell:cell];
[self.tableView reloadData];
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:ip.row+1 inSection:ip.section];
MyTableViewCell *theNewCell = (MyTableViewCell *)[self.tableView cellForRowAtIndexPath:nextIndexPath];
if (theNewCell) {
[theNewCell.textField becomeFirstResponder];
}
return YES;
}