Problem: The height of the keyboard is abnormal when it pops up in landscape mode
- (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];
}
Copy the code
So you pop up a new window, you have a UITextField in the rootViewController, and then you call becomeFirstResponder, and you launch your app, and the first time you pop up the keyboard, you walk into two notifications, and you print the height of the keyboard:
keyboardFrame height: 125.000000
keyboardFrame height: 302.000000
Copy the code
Both heights are wrong and cause the bar above the keyboard to be misplaced:
When the keyboard pops up for the second time: Print the keyboard height as:
keyboardFrame height: 248.000000
Copy the code
This is the normal height.
The first exception needs to be resolved.
Solve: directly take the child view judgment
The keyboard window has a subview UIInputSetHostView, which is the parent view of the keyboard display.
- (CGFloat)keyboardHeight {
UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] lastObject];
UIView *inputView = [keyboardWindow.rootViewController.view tkp_findSubview:@"UIInputSetHostView"];
if (inputView) {
return inputView.tkp_height;
}
return 0;
}
Copy the code
Where tkp_findSubview: method is the classification method of 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]) {
returnsubview; }}if (resursion) {
for (UIView *subview in self.subviews) {
UIView *tempView = [subview tkp_findSubview:name resursion:resursion];
if (tempView) {
returntempView; }}}return nil;
}
Copy the code