我有这个几乎填满整个UIViewController的UITableView,底部有一个包含按钮和文本字段的UIView。
当我点击文本字段时,我希望UIView和tableview向上推,这样UIView就在键盘顶部。
- UIView:
- UITextField
- UIButton
我在这里尝试了多个建议,但似乎没有一个在我的情况下有用。
答案 0 :(得分:13)
第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步:
管理约束作为键盘显示和隐藏通知,如下所示
- (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中的解决方案
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()
})
}
答案 1 :(得分:0)
如评论中所述,将每个@IBOutlet
的底部约束(包含文本字段和按钮的视图中的约束)连接到视图控制器。聆听UIKeyboardWillHideNotification
和UIKeyboardWillShowNotification
并实施他们的选择器。当键盘出现时,将底部约束调整到键盘高度,当它隐藏时,将其设置回0(或者你有的任何值)。我会将调整包装成动画。
喜欢(在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()
})
}
答案 2 :(得分:0)
一个词:约束。
在这里阅读我的文章: Height of iOS onscreen keyboard
它基本上在屏幕底部有一个约束,每当用户打开屏幕键盘时,它就会改变这个constaint的高度。
希望这有帮助。