将新单元格添加到UITableView时,选择UITableViewCell文本

时间:2013-04-11 12:25:58

标签: ios uitableview

我有一个基本UITableView,其中包含基本的UITableViewCell。当我向表中添加一个新单元格时,我想:

1)滚动到新行

2)选择新UITableViewCell中的所有文本,以便键盘可见,用户可以立即编辑单元格的文本。

下一次通过事件循环(在表视图上调用-reloadData之后)我这样做:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:wordIndex inSection:0];

[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionNone)];

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];  
[cell.textLabel becomeFirstResponder];
cell.highlighted = YES;

滚动是正确的,但未选中单元格中的文本。

2 个答案:

答案 0 :(得分:2)

UILabel无法成为第一响应者,因为它从NO返回canBecomeFirstResponder。为了表达已编辑标签的错觉,您可以尝试使用UITextField borderStyle UITextBorderStyleNone

请注意becomeFirstResponder调用的时间,因为如果控件不是窗口的子视图,则控件不能是第一响应者。如果您滚动到离屏幕很远的行并且在将becomeFirstResponder添加为可见行之前立即尝试调用{<1}},则会发生这种情况。

答案 1 :(得分:1)

与前面的答案一样,您可以创建UITableViewCell的自定义子项,在其上添加UITextField。

@interface MyTableViewCell : UITableViewCell
@property(nonatomic, retain) IBOutlet UITextField *editableTextField;
@end

您可以在控制器中捕获didSelectRowAtIndexPath并将其文本字段设置为第一响应者

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
[cell.editableTextField becomeFirstResponder];
}

UPD:作为上层答案描述的非窗口单元故障的故障解决方法,您必须在方法中调用selectCellAtIndexPath

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView