我在UIViewController
(不是UITableViewController
)上的表格 View 中有一个UITextField
。
如果表格 View 位于 UITableViewController
上,表格将自动滚动到正在编辑的 textField
以防止其被键盘隐藏。但在 UIViewController
上则不然。
我已经尝试了几天阅读多种方法来尝试完成此任务,但我无法让它发挥作用。实际滚动的最接近的东西是:
-(void) textFieldDidBeginEditing:(UITextField *)textField {
// SUPPOSEDLY Scroll to the current text field
CGRect textFieldRect = [textField frame];
[self.wordsTableView scrollRectToVisible:textFieldRect animated:YES];
}
但是,这只会将表格滚动到最上面一行。 看似简单的任务却经历了几天的挫折。
我使用以下内容来构造 tableView 单元格:
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = [NSString stringWithFormat: @"%d:%d", [indexPath indexAtPosition: 0], [indexPath indexAtPosition:1]];
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
UITextField *theTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 10, 130, 25)];
theTextField.adjustsFontSizeToFitWidth = YES;
theTextField.textColor = [UIColor redColor];
theTextField.text = [textFieldArray objectAtIndex:indexPath.row];
theTextField.keyboardType = UIKeyboardTypeDefault;
theTextField.returnKeyType = UIReturnKeyDone;
theTextField.font = [UIFont boldSystemFontOfSize:14];
theTextField.backgroundColor = [UIColor whiteColor];
theTextField.autocorrectionType = UITextAutocorrectionTypeNo;
theTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
theTextField.clearsOnBeginEditing = NO;
theTextField.textAlignment = UITextAlignmentLeft;
//theTextField.tag = 0;
theTextField.tag=indexPath.row;
theTextField.delegate = self;
theTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
[theTextField setEnabled: YES];
[cell addSubview:theTextField];
[theTextField release];
}
return cell;
}
我怀疑如果我能以某种方式在 textFieldDidBeginEditing
方法中传递 indexPath.row
,我就能让 tableView 正确滚动吗?
感谢任何帮助。
最佳答案
在我的应用程序中,我成功地使用了 contentInset
和 scrollToRowAtIndexPath
的组合,如下所示:
当您想要显示键盘时,只需在底部添加一个 contentInset 以及具有所需高度的表格:
tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
然后,您就可以放心使用了
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:cell_index inSection:cell_section] animated:YES];
通过添加 contentInset,即使您专注于最后一个单元格,tableView 仍然可以滚动。只需确保在关闭键盘时重置了 contentInset。
编辑:
如果您只有一个部分(可以将 cell_section
替换为 0),并使用 textView 标记来通知单元格行。
关于xcode - 获取 UITableView 滚动到选定的 UITextField 并避免被键盘隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5265559/