【发布时间】:2011-04-25 21:58:13
【问题描述】:
我有一个带有几个 UITableViewCells 的 UITableView,这些单元格内是 UITextFields。我实现了一个 UIToolbar 用于在不同的文本字段之间切换。我可以转到下一个单元格中的下一个文本字段或上一个文本字段。这可以正常工作,直到单元格成为当前在 tableview 中不可见的第一响应者。
我发现了
[self.tableview cellForRowAtIndexPath:indexPath]
返回nil 并且手动滚动到带有文本字段的单元格,它应该成为第一响应者,消除了问题。因此,我尝试滚动到单元格,然后再将其更改为第一响应者。
我试过了
[[self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
但不幸的是,tableview 不会滚动到这个单元格,而是滚动到所有其他单元格。当我在这一行添加断点时,问题不会发生。看起来表格视图正在滚动到单元格,但随后又向下滚动。
这里是cellForRowAtIndexPath的代码:
UITableViewCell *cell;
static NSString *AttributeCellIdentifier = @"AttributeCellIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AttributeCellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"AttributeCell" owner:self options:nil];
cell = attributeCell;
self.attributeCell = nil;
UITextField * textField = (UITextField *)[cell viewWithTag:1];
[textField setKeyboardType:UIKeyboardTypeDecimalPad];
[textField setInputAccessoryView:[self inputAccessoryView]];
}
UITextField * textField;
textField = (UITextField *)[cell viewWithTag:1];
textField.placeholder = @"C(Probe)/mol/l";
return cell;
这是切换到上一个文本字段的代码:
UIView * currentResponder = [self.view findFirstResonder];
UITextField * newFocusTextField;
UITableViewCell * cell = (UITableViewCell*)[[currentResponder superview] superview];
NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
newFocusTextField = (UITextField*)[[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]] viewWithTag:1];
[currentResponder resignFirstResponder];
[newFocusTextField becomeFirstResponder];
UITableViewCell * newCell = (UITableViewCell*)[[newFocusTextField superview] superview];
NSIndexPath * newIndexPath = [self.tableView indexPathForCell:newCell];
[self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
希望这会有所帮助。
【问题讨论】:
-
请贴出 cellForRowAtIndexPath 的代码。这个方法的内容你写了吗?如果是这样,为什么它返回零?如果没有,为什么不呢?
-
我写了那个代码,我认为它返回 nil 因为滚动不起作用时单元格不可见。来自 cellForRowAtIndexPath 的文档:表示表格单元格的对象,如果单元格不可见或 indexPath 超出范围,则为 nil。
-
当您点击工具栏以显示/编辑文本字段时,它是如何实现的?我想知道这里是否存在排序问题,即您可能需要滚动表格以先显示单元格,然后使其成为第一响应者。
-
@Mike - 我明白你的意思,我试过了,但这并不能解决问题。
标签: iphone objective-c cocoa-touch uitableview