键盘弹起遮住输入框这个问题是每个iOS开发者绕不过去的坎,那么到底该如何进行键盘处理?
现在有TPKeyboardAvoiding和IQKeyboardManager这两个大牛级的库,其实自己做起来也比较简单:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardFrameChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)handleKeyboardFrameChange:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
if (CGRectIsNull(keyboardEndFrame)) {
return;
}
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat height = 0.0;
if (fabs(keyboardEndFrame.origin.y - screenHeight) > 0.1) {
height = CGRectGetHeight(keyboardEndFrame);
}
double animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
self.bottomConstraint.constant = height;
[UIView animateWithDuration:animationDuration animations:^{
[self.view layoutIfNeeded];
}];
}
这里只用监听一个通知UIKeyboardDidChangeFrameNotification即可,并不其他很多文章里面描述的需要监听UIKeyboardWillShowNotification,UIKeyboardDidShowNotification,UIKeyboardWillHideNotification,UIKeyboardDidHideNotification等通知。然后获取keyboardEndFrame的高度即可。
网友评论