转到不同UITableViewCells中的下一个UITextField

时间:2013-08-23 18:22:37

标签: ios uitableview uitextfield

我有UITableView个x个单元格。在某些单元格中有x个UITextFields。我希望键盘上的下一个按钮突出显示下一个textField。我让它在同一个单元格中工作,但是当它应该跳转到另一个单元格中的textField时却没有。每个单元格中的第一个textField标记为0,第二个标记为1,依此类推。这是我的代码:

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    // Fetch current cell
    UITableViewCell *cell = (UITableViewCell *)textField.superview.superview;

    // Tag for next textField
    NSInteger nextTag = textField.tag + 1;

    UITextField *nextTextField;

    for(UITextField *subview in cell.contentView.subviews){

        if([subview isKindOfClass:[UITextField class]]){

            if(subview.tag == nextTag){

                nextTextField = subview;
                break;

            }

        }

    }

    if(nextTextField){

        // Go to next textField
        [nextTextField becomeFirstResponder];

    } else{

        // IndexPath for current cellen
        NSIndexPath *indexPath = [travellersTableView indexPathForCell:cell];

        UITableViewCell *nextCell;

        // While a cell exist at indexPath
        while([travellersTableView numberOfSections] > indexPath.section+1){

            nextCell = [self tableView:travellersTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section+1]];

            if(nextCell){

                for(UITextField *subview in nextCell.contentView.subviews){

                    if([subview isKindOfClass:[UITextField class]]){

                        if(subview.tag == 0){

                            NSLog(@"%@", subview.placeholder);

                            nextTextField = subview;
                            break;

                        }

                    }

                }

                // Go to next textField or cell
                if(nextTextField){
                    [nextTextField becomeFirstResponder]; NSLog(@"Next!");
                    break;
                } else{
                    indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section+1];
                }

            }

        }

        if(!nextTextField){ [textField resignFirstResponder]; }

    }

    return NO;

}

NSLog的行为符合预期。我在textFields中有不同的占位符,下一个占位符被回显。下一个!也是如此,它正在尝试becomeFirstResponder

2 个答案:

答案 0 :(得分:1)

我发现了这个问题。我没有正确地从tableView中获取nextCell。这就是它应该是这样的:

nextCell = [travellersTableView cellForRowAtIndexPath:indexPath];

答案 1 :(得分:0)

始终从至少1开始标记。等于零的标记会导致严重问题。标记为0的对象通常不会初始化。从1开始标记并再次检查。