当键盘不隐藏文本字段时移动视图

在我的应用程序中,当我点击文本字段时,键盘隐藏它。 请帮助我 – 当我点击文本字段时,如何移动我的视图。 我在textFieldDidBeginEditing:使用这个代码textFieldDidBeginEditing:

 self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 216, 0); self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0); 

但它不起作用。

您可以执行以下操作,但首先确保已将UITextField委托设置为您自己和

 #define kOFFSET_FOR_KEYBOARD 350; 

在顶部。 这是你想要移动视图的距离

 //method to move the view up/down whenever the keyboard is shown/dismissed -(void)setViewMovedUp:(BOOL)movedUp { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; // if you want to slide up the view [UIView setAnimationBeginsFromCurrentState:YES]; CGRect rect = self.view.frame; if (movedUp) { // 1. move the view's origin up so that the text field that will be hidden come above the keyboard // 2. increase the size of the view so that the area behind the keyboard is covered up. if (rect.origin.y == 0 ) { rect.origin.y -= kOFFSET_FOR_KEYBOARD; //rect.size.height += kOFFSET_FOR_KEYBOARD; } } else { if (stayup == NO) { rect.origin.y += kOFFSET_FOR_KEYBOARD; //rect.size.height -= kOFFSET_FOR_KEYBOARD; } } self.view.frame = rect; [UIView commitAnimations]; } - (void)keyboardWillHide:(NSNotification *)notif { [self setViewMovedUp:NO]; } - (void)keyboardWillShow:(NSNotification *)notif{ [self setViewMovedUp:YES]; } - (void)textFieldDidBeginEditing:(UITextField *)textField { stayup = YES; [self setViewMovedUp:YES]; } - (void)textFieldDidEndEditing:(UITextField *)textField { stayup = NO; [self setViewMovedUp:NO]; } - (void)viewWillAppear:(BOOL)animated { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:self.view.window]; } - (void)viewWillDisappear:(BOOL)animated { // unregister for keyboard notifications while not visible. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; } 

您不应该相信textFieldDidBeginEditing:要调整键盘,因为即使用户使用不显示屏幕键盘的物理键盘键入,也会调用此方法。

相反,要听取UIKeyboardWillShowNotification ,只有在键盘实际显示时才会触发。 你需要做三个步骤:

  1. 从通知userInfo字典中确定键盘的实际大小。 尺寸将不同于风景/肖像以及不同的设备。
  2. 使用确定的大小更新contentInset 。 你可以做animation,通知甚至会告诉你键盘animation的持续时间。
  3. 将文本框滚动到视图中,很容易忘记这一点!

您可以从这里find更多信息和示例代码