摘抄网站:http://www.aichengxu.com/view/46396
ps:当时的情况--一个界面上有5个textField,布局全手写,下面有提到的sv也就是我那些触发键盘弹出的textFiled了。针对不同的textField,设置tag值,并在代理方法textFieldShouldBeginEditing:中赋值_textField供计算viewBottom。(_textField是定义的属性)
~~~~~~~~这并不是浪、只是分割线~~~~~~~~
这里介绍的解决方案是通过Apple系统提供的通知来解决问题,NSNotification中包含了键盘的一些信息,这个可以充分利用之。
首先监听以下两个通知,系统会负责发送通知,当然你自己也可以发送。
// 监听键盘的即将显示事件. UIKeyboardWillShowNotification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; // 监听键盘即将消失的事件. UIKeyboardWillHideNotification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
实现通知处理方法
- (void) keyboardWillShow:(NSNotification *)notify { //这里只写了关键代码,细节根据自己的情况来定,sv为弹出键盘的视图,UITextField CGFloat kbHeight = [[notify.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;//获取键盘高度,在不同设备上,以及中英文下是不同的,很多网友的解决方案都把它定死了。 // 取得键盘的动画时间,这样可以在视图上移的时候更连贯 double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGFloat screenHeight = self.view.bounds.size.height; CGFloat viewBottom = sv.frame.origin.y + sv.frame.size.height; if (viewBottom + kbHeight < screenHeight) return;//若键盘没有遮挡住视图则不进行整个视图上移 // 键盘会盖住输入框, 要移动整个view了 delta = viewBottom + kbHeight - screenHeight + 50; // masonry的地方了 mas_updateConstraints 更新superView的约束,这里利用第三方库进行了重新自动布局,如果你不是自动布局,这里换成你的视图上移动画即可 [superView mas_updateConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.view.mas_top).offset(-delta); }]; [UIView animateWithDuration:duration animations:^void(void){ // superView来重新布局 [superView layoutIfNeeded]; }]; }
- (void) keyboardWillHidden:(NSNotification *)notify {//键盘消失 // 键盘动画时间 double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; [superView mas_updateConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.view.mas_top); }]; [UIView animateWithDuration:duration animations:^{ [superView layoutIfNeeded]; }]; delta = 0.0f; }