获取UITextFell上的UITextField的引用?

时间:2011-09-08 17:36:43

标签: iphone objective-c ios uitableview

实际上我正在使用下一个和上一个按钮将一个单元格移动到另一个单元格,每个单元格都有一个文本字段,所以当我点击下一个按钮时,它会将我移动到下一个单元格并通过获取此单元格引用我可以创建文本字段成为第一响应者,但当我点击上一个按钮时,它返回我没有参考。 我用于下一个和上一个的代码如下所示

- (IBAction)nextPrevious:(id)sender
{
    NSIndexPath *indexPath ;
    BOOL check = FALSE;

    if([(UISegmentedControl *)sender selectedSegmentIndex] == 1){
        if(sectionCount>=0 && sectionCount<8){
            //for next button
            check = TRUE;
            sectionCount = sectionCount+1;
            indexPath = [NSIndexPath indexPathForRow:0 inSection:sectionCount];
        }
    }else{
        //for previous button
        if(sectionCount>0 && sectionCount<=9){
            check = TRUE;
            sectionCount = sectionCount-1;

            indexPath = [NSIndexPath indexPathForRow:0 inSection:sectionCount];
        }
    }

    if(check == TRUE){
        //[registrationTbl reloadData];
        UITableViewCell *cell = [registrationTbl cellForRowAtIndexPath:indexPath];

        for(UIView *view in cell.contentView.subviews){
            if([view isKindOfClass:[UITextField class]]){
                    [(UITextField *)view becomeFirstResponder];
                    break;
            }
        }

        [registrationTbl scrollToRowAtIndexPath:indexPath
                               atScrollPosition:UITableViewScrollPositionTop
                                       animated:YES];


        // UITextField *field = (UITextField *) [cell.contentView viewWithTag:indexPath.section];
        // [field becomeFirstResponder];
    }

任何小建议都将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:1)

问题在于滚动。当您滚动到下一行的顶部时,前一行将被删除并重新用于最后一个可见行,这意味着方法cellForRowAtIndexPath:可能会返回null,因为该单元格当前不可用。

快速和肮脏的修复将涉及滚动到中间或稍微移位,以便细胞仍然可见。不那么快也不脏将涉及制作一个滚动表格以确保单元格可见的过程,然后当滚动停止时,将文本字段设置为第一个响应者。

编辑)再解释一下这最后一种方法。假设您添加了一个新变量NSIndexPath *indexPathEditing。委托方法tableView:cellForRowAtIndexPath:将具有:

if (indexPathEditing && indexPathEditing.row == indexPath.row && indexPathEditing.section == && indexPath.section)
{
    // Retrieve the textfield with its tag.
    [(UITextField*)[cell viewWithTag:<#Whatever#>] becomeFirstResponder];
    indexPathEditing = nil;
}

这意味着如果设置indexPathEditing,并且当前正在加载的行可见,它将自动将其自身设置为firstResponder

然后,例如(在您的nextPrevious:方法中),您需要做的就是:

indexPathEditing = [NSIndexPath indexPathForRow:0 inSection:sectionCount];

[registrationTbl scrollToRowAtIndexPath:indexPathEditing
                       atScrollPosition:UITableViewScrollPositionTop
                               animated:YES];
[registrationTbl reloadData];

该行将显示,tableView:cellForRowAtIndexPath:被调用,它将自动设置为firstResponder

另外,请注意,不是使用isKindOfClass执行for,而是更容易设置标记号,然后使用viewWithTag:检索对象,我在示例中将其合并。