问题描述
|
这肯定是一个常见的问题...我在表格单元格中有一个
UITextField
,我想让用户对其进行编辑。但是,当键盘出现时,它通常会遮盖文本字段。
我试过使用scrollToRowAtIndexPath:atScrollPosition
,但是令人惊讶的是,这行不通。我尝试将UITableViewScrollPosition
设置为{None,Top,Button,Middle}
。
滚动丢失的秘诀是什么?
谢谢。
解决方法
秘密在于您必须手动实现该行为,这很痛苦。
您必须采取一些步骤:
步骤1:注册键盘通知
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}
步骤2:当键盘出现时,调整内容插图的大小
- (void)keyboardWasShown:(NSNotification *)notification {
NSDictionary* info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0f,0.0f,kbSize.height,0.0f);
self.tableview.contentInset = contentInsets;
self.tableview.scrollIndicatorInsets = contentInsets;
[self.scrollView scrollRectToVisible:self.selectedView.frame animated:YES];
}
假定您在类中有一个名为“ selectedView \”的属性。还有其他方法可以做到这一点,但主要的是,您需要以某种方式知道用户需要查看的视图。
步骤3:键盘消失后,重置表格视图
- (void)keyboardWillBeHidden:(NSNotification *)notification {
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.tableview.contentInset = contentInsets;
self.tableview.scrollIndicatorInsets = contentInsets;
}
步骤4:取消注册通知
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
}
, 那么,表格单元格是否隐藏了文本字段?为什么要通过滚动解决它?更改将文本字段添加到单元格的方式。