我已经尝试了 this thread 中的一些解决方案,但我遇到了麻烦。我的表是动态加载 plist 中的数据的,因此我无法在 Storyboard中创建从一个单元格到另一个单元格的连接。我实现了一个名为 DSCell 的自定义 UITableViewCell 类,它在单元格的右侧有两个 DSTextField 对象。当在最左边的 DSTextField 上按 Enter 键时,它成功地将焦点转移到下一个字段。但是,当在右侧文本字段中按 Enter 时,它应该将焦点移动到下一个单元格中的文本字段(向下一行)。但事实并非如此。
单元格中的文本字段具有标签 2 和 3。
这是我的 cellForRowAtIndex 方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"PaperCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSString *text = [_paper objectAtIndex:indexPath.row];
UILabel *label = (UILabel *)[cell viewWithTag:1];
label.text = text;
// Set the "nextField" property of the second DSTextfield in the previous cell to the first DSTextField
// in the current cell
if(indexPath.row > 0)
{
DSCell *lastcell = (DSCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]];
DSTextField *lastField = (DSTextField *)[lastcell viewWithTag:3];
DSTextField *currentField = (DSTextField *)[cell viewWithTag:2];
lastField.nextField = currentField;
}
return cell;
}
这是 textFieldShouldReturn 方法:
- (BOOL) textFieldShouldReturn:(UITextField *) textField {
DSTextField *field = (DSTextField *)textField;
UIResponder *responder = field;
[responder resignFirstResponder];
responder = field.nextField;
[responder becomeFirstResponder];
return YES;
}
当前,我尝试在调用 cellForRowAtIndexPath 时将第二个 DSTextField 的 nextField 属性设置为当前单元格,但它似乎不起作用。我从第 1 行开始,尝试检索前一行中的单元格,然后将最右侧文本字段的 nextField 属性分配给当前单元格中最左侧文本字段。
有更好的方法吗?我不想为每个文本字段使用不同的标签并这样做,这可能会变得困惑。
最佳答案
我建议您只尝试在 textFieldShouldReturn:
方法中找到将焦点转移到的正确单元格。可能导致问题的一件事是您可能请求单元格成为不可见的 lastCell
,然后由 tableview 处理(因此 nextField
是无效)。
更改事物返回时发生的逻辑(您仍然希望在一行中的两个单元格之间设置 nextField
):
- (BOOL) textFieldShouldReturn:(UITextField *) textField {
//This isn't necessary: UIResponder *responder = field;
//Or this: [responder resignFirstResponder];
//Check if it's the left or right text field
if (textField.tag == 3) {
//Find the cell for this field (this is a bit brittle :/ )
UITableViewCell *currentCell = textField.superview.superview;
NSIndexPath *ip = [self.tableView indexPathForCell:currentCell];
if (ip.row < [self.tableView numberOfRowsInSection:ip.section] - 1) {
DSCell *nextCell = (DSCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:ip.row+1 inSection:ip.section]];
[[nextCell viewWithTag:2] becomeFirstResponder];
}
}
return YES;
}
关于ios - 点击下一步/完成时在不同 UITableViewCell 中的 UITextField 中导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14528890/