就是通过系统的一个通知,获取到键盘即将展示,和即将消失的时机,并通过
通知获取到键盘的高度和键盘弹出的duration, 我们上移页面frame的时候也用这个
duration,就能产生和键盘同步移动的效果,下面是代码
添加和移除通知监听
- (void)addKeyboardObserver {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillDisappear:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)removeKeyboardObserver {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
在监听方法中修改视图的frame
- (void)keyboardWillShow:(NSNotification *)noti
{
CGRect keyboardRect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat boardHeight = keyboardRect.size.height;
CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
LIVWeakify(self);
[UIView animateWithDuration:duration animations:^{
LIVStrongify(self);
self.viewContent.y -= boardHeight;
}];
[self.viewContent addGestureRecognizer:self.endEditingTap];
}
- (void)keyboardWillDisappear:(NSNotification *)noti
{
CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
LIVWeakify(self);
[UIView animateWithDuration:duration animations:^{
LIVStrongify(self);
self.viewContent.y = self.view.height * 0.25;
}];
[self.viewContent removeGestureRecognizer:self.endEditingTap];
}