移动到分组TableView中不同单元格中的下一个UITextField



我有一个添加了分组表视图的ViewController。某些单元格包含文本字段。当用户按下回车键时,我想将第一个响应程序切换到单元格列表中的下一个文本字段。但是,我无法让它工作,我也无法判断我是选择了错误的单元格还是选择了不正确的文本字段。

我正在cellForRowAtIndexPath中使用以下内容设置标记。。

cell.tag = ((indexPath.section + 1) * 10) + indexPath.row;

这将创建一个标记,其中十位为节值,一位为行值。即标签11是第0节第1行。

这是我的文本字段应该返回的代码

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
UITableViewCell *cell = (UITableViewCell *)textField.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
cell = [self tableView:_tableView cellForRowAtIndexPath:indexPath];
if (indexPath.section == 0)
{
    if (indexPath.row == 0)
    {
        [[cell viewWithTag:((indexPath.section + 1) * 10) + (indexPath.row + 1)] becomeFirstResponder];
    }
    if (indexPath.row == 1)
    {
        [[cell viewWithTag:((indexPath.section + 2) * 10)] becomeFirstResponder];
    }
}
return YES;
}

最后要注意的是,目前新标记的增量是硬编码的,但我希望能够转到新标记,而不必每次都硬编码实际值。这可能吗?

如果您的所有单元格都包含1个UITextField,我认为您可以将UITableViewCell子类化,并添加一个引用单元格文本字段的属性,就像我在这里所做的那样。

但是您说只有一些单元格包含文本字段,所以另一种选择是创建一个指向UITextFields的指针数组(我在这里得到了这个想法)。然后按下Return的用户会像这样循环:

- (BOOL) textFieldShouldReturn:(UITextField*)textField {
    NSUInteger currentIndex = [arrayOfTextFields indexOfObject:textField] ;
    if ( currentIndex < arrayOfTextFields.count ) {
        UITextField* nextTextField = (UITextField*)arrayOfTextFields[currentIndex+1] ;
        [nextTextField becomeFirstResponder] ;
    }
    else {
        [textField resignFirstResponder] ;
    }
}

将标记设置为textField,而不是单元格。

yourTextField.tag = ((indexPath.section + 1) * 10) + indexPath.row;

相关内容

最新更新