iOS 11 - 键盘高度在键盘通知中返回0

问题描述:

我一直在使用键盘通知没有任何问题,并获得键盘的确切高度。iOS 11 - 键盘高度在键盘通知中返回0

- (void)keyboardDidShow:(NSNotification *) notification{ 
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 

    NSLog(@"%f",keyboardSize.height);} 

但在iOS 11中,调用通知时键盘的大小为0。

在这种情况下发生了什么问题?我使用的Xcode 9 Beta版5

使用此:

CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; 

对于斯威夫特,你可以使用:

let keyboardSize = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size 
+1

你救了我的一天 –

+1

感谢,决不会想到 –

+3

改变从UIKeyboardFrameBeginUserInfoKey到UIKeyboardFrameEndUserInfoKey的伎俩,THX的。 – user2408952

更换UIKeyboardFrameBeginUserInfoKey

UIKeyboardFrameEndUserInfoKey

以下是Apple Docs。

UIKeyboardFrameBeginUserInfoKey-用于容纳的CGRect标识在屏幕坐标键盘 的起始帧的NSValue对象 的键。

UIKeyboardFrameEndUserInfoKey - 包含CGRect的NSValue对象 的密钥,该CGRect标识屏幕坐标中的键盘末端帧。

+10

然后Apple需要更新他们的示例代码,因为它在iOS 11上不再工作。另外从Apple文档中,他们使用UIKeyboardFrameBeginUserInfoKey:https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual /TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html – wildcat12

+0

解决了我的问题!感谢您的建议! – Ernie

+0

有人能像我这样向我解释5岁时这两者之间的区别是什么,为什么这会使UIScrollView自动滚动时发生变化?我真的很感激。谢谢! – Mario

试试这个:

更换UIKeyboardFrameBeginUserInfoKeyUIKeyboardFrameEndUserInfoKey

+1

'[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame :) name:UIKeyboardWillChangeFrameNotification object:nil];'method keyboardWillChangeFrame:不仅可以运行一次,也可以两次或更多。有时键盘上有时会有特殊的工具栏,此时该方法会运行很多次。因此,您应该将** UIKeyboardFrameBeginUserInfoKey **替换为** UIKeyboardFrameEndUserInfoKey **得到键盘的最后一帧。 – SolinLiu

我使用的Xcode 9.0版(9A235)也有类似的问题;虽然我在使用Swift。在我keyboardWillShow方法我写了下面:

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { 

    let heightValue = keyboardSize.height  

    ... 
} 

奇怪的是,在第一时间keyboardWillShow叫,heightValue为216.0,但在随后的通话,它已成为0!也许这是一个Xcode错误。

我用UIKeyboardFrameEndUserInfoKey替换了UIKeyboardFrameBeginUserInfoKey,它解决了我的问题。

+1

我注意到了同样的事情。它似乎也只适用于第一次键盘显示。第一次显示该视图控制器时,其他视图控制器上的键盘报告高度为0。 – jackofallcode

这个问题是发生在iOS上11

如下图所示,将解决这个问题 “UIKeyboardFrameEndUserInfoKey”

更换

“UIKeyboardFrameBeginUserInfoKey”

的Objective-C代码:

CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; 

Swift 2。3:

let keyboardSize = (NfnPsgVar.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue().size 

斯威夫特3:

let keyboardSize = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size