【问题标题】:Bring up Keyboard for cell in UITableView?在 UITableView 中为单元格调出键盘?
【发布时间】:2009-08-04 03:34:17
【问题描述】:

我有 UITableView,它有代表玩家的自定义单元格。当我添加一个新播放器时,会添加一个新数据项并调用 [UITableView reloadData]。单元格的一部分是包含玩家名称的 UITextView。如何调出键盘?

如果我可以访问单元格中的 UITextView 但实际上尚未创建它,我可以使用 becomeFirstResponder。由于 reloadData 实际上还没有执行新单元格的创建。

以前一定有人解决过这个问题。任何有关如何完成这项工作的提示将不胜感激。

我的代码sn-p:

-(IBAction)addPlayerPressed:(id)sender {
Player *newPlayer = [Player alloc];
[players addObject:newPlayer];
[table reloadData];

// Scroll to bottom showing the new player location
NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([players count] - 1) inSection:0];
[table scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

// cell is always nil  :(
PlayerTableCell *cell = (PlayerTableCell *)[table cellForRowAtIndexPath:scrollIndexPath]
[cell.nameField setfirstResponder];
}

【问题讨论】:

    标签: iphone uitableview


    【解决方案1】:

    几件事:

    您最好使用 UITextField 而不是 UITextView。 UITextField 非常适合您在此处描述的单行条目。

    至于您的解决方案,我建议您这样做。 (还冒昧清理了你的内存管理)

    向您的 Player 类添加一个 BOOL 属性,例如“needsKeyboardDisplay”,然后在创建新实例后将其设置为 yes。

    -(IBAction)addPlayerPressed:(id)sender {
    Player *newPlayer = [[Player alloc] init];
    
    
    newPlayer.needsKeyboardDisplay = YES;
    
    
    [players addObject:newPlayer];
    
    [newPlayer release];
    
    [table reloadData];
    
    // Scroll to bottom showing the new player location
    
    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([players count] - 1) inSection:0];
    
    [table scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    
    }
    

    然后,在 cellForRowAtIndexPath 中,在您以其他方式设置单元格后插入它:

    Player *playerForCell = [players objectAtIndex:indexPath.row]; 
    
    if (playerForCell.needsKeyboardDisplay)
    {
    [nameField becomeFirstResponder];
    playerForCell.needsKeyboardDisplay = NO;
    }
    

    总而言之,从用户体验的角度来看,在这样的一长串项目中编辑细节的(有点)标准 iPhone 体验是在另一个视图中进行。当然,这取决于你。

    【讨论】:

    • 我收回了这一点,这个修复似乎严重破坏了 UITableView。添加和删​​除几行后,显示变得非常混乱。我的数据集和报告为呈现的实际单元格看起来正确,但显示本身显示重复条目。注释掉显示键盘的代码会使应用程序恢复正常功能。 :(
    【解决方案2】:

    你可以让文本字段委托 UITableviewController 而不是表格单元格吗?

    【讨论】:

      【解决方案3】:

      在您的 PlayerTableCell 类中,您可以在 -initWithStyle:reuseIdentifier: 方法中添加一些代码,以检查它是否应该成为第一响应者,如果是,则这样做。你可能有一个 PlayerController 类或类似的东西;您可以为自定义表格视图单元格或类似的东西创建一个委托方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-15
        相关资源
        最近更新 更多