iOS横屏弹键盘的高度错误异常解决

来自:互联网
时间:2021-04-15
阅读:

问题:横屏下第一次弹出键盘高度异常

- (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

这两个高度都是错误的,会导致键盘上面的工具条错位:

iOS横屏弹键盘的高度错误异常解决

第2次弹出键盘时:打印键盘高度为:

keyboardFrame height: 248.000000

这时候就是正常的高度了。

需要解决第一次异常的问题。

解决:直接取子view判断

iOS横屏弹键盘的高度错误异常解决

查看层级,发现键盘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;
}
返回顶部
顶部