iOS横屏弹键盘的高度错误异常解决
问题:横屏下第一次弹出键盘高度异常
- (void)handleKeyboardWillShowNotification:(NSNotification *)notification { NSTimeInterval animationDuration = 0; CGRect keyboardFrame = CGRectZero; NSDictionary *userInfo = [notification userInfo]; [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration]; [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame]; printf("keyboardFrame height: %f\n", keyboardFrame.size.height); [self showWithAnimationDuration:animationDuration keyboardFrame:keyboardFrame]; }
弹出新window,rootViewController里面有个 UITextField ,然后调用 becomeFirstResponder ,启动app,第1次弹出键盘时,会走进两次通知,打印键盘高度:
keyboardFrame height: 125.000000 keyboardFrame height: 302.000000
这两个高度都是错误的,会导致键盘上面的工具条错位:
第2次弹出键盘时:打印键盘高度为:
keyboardFrame height: 248.000000
这时候就是正常的高度了。
需要解决第一次异常的问题。
解决:直接取子view判断
查看层级,发现键盘window有个子view UIInputSetHostView,这就是键盘显示的父view,这时候取得这个view,也就取得了键盘的真正高度:
- (CGFloat)keyboardHeight { UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] lastObject]; UIView *inputView = [keyboardWindow.rootViewController.view tkp_findSubview:@"UIInputSetHostView"]; if (inputView) { return inputView.tkp_height; } return 0; }
其中 tkp_findSubview: 方法为 UIView 的分类方法:
- (UIView *)tkp_findSubview:(NSString *)name { return [self tkp_findSubview:name resursion:NO]; } - (UIView *)tkp_findSubview:(NSString *)name resursion:(BOOL)resursion { Class class = NSClassFromString(name); for (UIView *subview in self.subviews) { if ([subview isKindOfClass:class]) { return subview; } } if (resursion) { for (UIView *subview in self.subviews) { UIView *tempView = [subview tkp_findSubview:name resursion:resursion]; if (tempView) { return tempView; } } } return nil; }
总结
到此这篇关于iOS横屏弹键盘的高度错误异常解决的文章就介绍到这了,更多相关iOS横屏弹键盘高度内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)