获取UITableViewCell上的UITextField的引用?

问题描述:

其实我正在使用下一个和上一个按钮将一个移动到另一个单元格,并且每个单元格都有一个文本字段,因此当我单击下一个按钮时,它会将我移动到下一个单元格,并且通过获取此单元格引用可以使文本字段变为第一响应者,但是当我点击上一个按钮时,它返回我没有参考。 其中我使用了一个和前一个下面的代码获取UITableViewCell上的UITextField的引用?

- (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]; 
    } 

给出的任何小建议将不胜感激。在此先感谢

问题就出在滚动。当您滚动到下一行的顶部时,上一行将被删除并重新用于最后一个可见行,这意味着方法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,它更容易设置标签号码,然后用viewWithTag:检索的对象,在我的例子将这一。

+0

非常感谢,非常感谢,非常好。它为我工作。 –