我有UITableView
,我是通过自定义UIViewController
控制的。当用户点击“添加”按钮时,我会在UITableView
中添加一行,其中包含文本字段,并将其作为第一个响应者。问题是,当表格底部不在视野范围内(或被键盘隐藏)时,UITableView
不会滚动以显示文本字段。
UITableViewController
会自动执行此操作,但我的视图控制器不能是UITableViewController
的子类。
答案 0 :(得分:9)
我通过在键盘出现或消失时contentInset
上UITableView
来修复此问题。
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification *)aNotification {
CGRect keyboardBounds;
[[aNotification.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
keyboardHeight = keyboardBounds.size.height;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
[UIView commitAnimations];
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[items count] inSection:0]
atScrollPosition:UITableViewScrollPositionMiddle
animated:YES];
}
- (void)keyboardWasHidden:(NSNotification *)aNotification {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
tableView.contentInset = UIEdgeInsetsZero;
[UIView commitAnimations];
}
在您加载registerForKeyboardNotifications
时致电UITableView
,其他一切都应该正常工作。
答案 1 :(得分:0)
我找到-scrollToRowAtIndexPath:atScrollPosition:animated:
并猜测这会做你想要的。
答案 2 :(得分:0)
我遇到了类似的问题,这是我的问题:http://www.passiondeveloper.com/discussion/8/uitableview-inline-editing-with-a-textfield-inside-uitableview-not-scrolling-when-keyboard-is-shown
答案 3 :(得分:0)
为ios5工作
UITextField *activeField;
// Called when the UIKeyboardDidShowNotification is sent.
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWasShown:(NSNotification *)aNotification {
id view = [activeField superview];
while (view && ![view isKindOfClass:[UITableViewCell class]])
{
view = [view superview];
}
UITableViewCell *cell = view;
NSIndexPath *indexPath = [tableview indexPathForCell:cell];
CGRect keyboardBounds;
[[aNotification.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
tableview.contentInset = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
[UIView commitAnimations];
[tableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)keyboardWasHidden:(NSNotification *)aNotification {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
tableview.contentInset = UIEdgeInsetsZero;
[UIView commitAnimations];
}