UITableView和UIView与keyboardWillShow

我有这个UITableView几乎填充我的整个UIViewController,我有一个UIView在底部包含一个button和一个文本框。

当我点击文本框时,我想让UIView和tableview向上推,这样UIView就在键盘之上。

- UIView: - UITextField - UIButton 

我已经在这里尝试了多个build议,但似乎没有在我的情况下工作。

一个字:限制。

在这里阅读我的文章: iOS屏幕键盘的高度

它基本上在屏幕底部有一个约束,每当用户打开屏幕键盘时,它会改变这个constaint的高度。

在这里输入图像描述

希望这可以帮助。

步骤1:
做一个UIView底部约束的出口

在这里输入图像描述

第2步:
添加键盘显示和隐藏的观察者,然后根据键盘高度改变约束常量。

 //**In viewDidLoad method** // register for keyboard notifications [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; // register for keyboard notifications [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; 

第3步:
像键盘显示和隐藏通知一样pipe理约束如下

 - (void)keyboardWillShow:(NSNotification *)notification { NSDictionary* userInfo = [notification userInfo]; // get the size of the keyboard CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; CGSize keyboardSizeNew = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; [UIView animateWithDuration:0.2 animations:^{ _bottomConstraintofView.constant = keyboardSizeNew.height; [self.view layoutIfNeeded]; // Called on parent view }]; } - (void)keyboardWillHide:(NSNotification *)notification { [UIView animateWithDuration:0.2 animations:^{ _bottomConstraintofView.constant = 0; [self.view layoutIfNeeded]; }]; } 

在Swift中的解决scheme

 func keyboardWillShow(notification: NSNotification){ let userInfo:NSDictionary = notification.userInfo! let keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size let keyboardSizeNow:CGSize = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue().size UIView.animateWithDuration(0.2, animations: { () -> Void in self.bottomConstraintofView.constant = keyboardSizeNow.height self.view.layoutIfNeeded() }) } func keyboardWillHide(notification: NSNotification){ UIView.animateWithDuration(0.2, animations: { () -> Void in self.bottomConstraintofView.constant = 0 self.view.layoutIfNeeded() }) } 

正如在评论中提到的那样,将每个@IBOutlet的底部约束(包含文本字段和button的底部约束) @IBOutlet到您的视图控制器。 收听UIKeyboardWillHideNotificationUIKeyboardWillShowNotification并实施其select器。 当出现键盘时,将底部约束调整到键盘高度,并在隐藏时将其设置回0(或您在其中的任何值)。 我会在animation中包装调整。

像(在Swift中):

 func keyboardWillShow(notification: NSNotification) { var info = notification.userInfo! var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() self.view.layoutIfNeeded() UIView.animateWithDuration(0.25, animations: { () -> Void in self.bottomConstraint.constant = keyboardFrame.size.height self.view.layoutIfNeeded() }) } func keyboardWillHide(notification: NSNotification) { self.view.layoutIfNeeded() UIView.animateWithDuration(0.25, animations: { () -> Void in self.bottomConstraint.constant = 0 self.view.layoutIfNeeded() }) }