无法在iOS8中获得正确的键盘高度值

我正在使用此代码来确定键盘的大小:


- (void)keyboardWillChange:(NSNotification *)notification {

    NSDictionary* keyboardInfo = [notification userInfo];

    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];

    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];


}

我正在模拟器中运行它。


问题是因为iOS 8不会给出正确的值,如果键盘建议是向上的,或者如果我按下它们,则会得到不同的(不正确的)值。


如何获得包括键盘建议在内的键盘的确切尺寸?


POPMUISE
浏览 860回答 3
3回答

LEATH

采用NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];

慕尼黑5688855

随着iOS中自定义键盘的引入,这个问题变得更加复杂。简而言之,UIKeyboardWillShowNotification可以通过自定义键盘实现多次调用:当苹果的系统键盘被打开(纵向)发送的UIKeyboardWillShowNotification的键盘高度为224当了Swype键盘被打开(纵向):发送的UIKeyboardWillShowNotification的键盘高度为0发送的UIKeyboardWillShowNotification的键盘高度为216发送的UIKeyboardWillShowNotification的键盘高度为256当SwiftKey键盘被打开(纵向):发送的UIKeyboardWillShowNotification的键盘高度为0发送的UIKeyboardWillShowNotification的键盘高度为216发送的UIKeyboardWillShowNotification的键盘高度为259为了在一个代码行中正确处理这些情况,您需要:根据UIKeyboardWillShowNotification和UIKeyboardWillHideNotification通知注册观察者:[[NSNotificationCenter defaultCenter] addObserver:self                                         selector:@selector(keyboardWillShow:)                                             name:UIKeyboardWillShowNotification                                           object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self                                         selector:@selector(keyboardWillHide:)                                             name:UIKeyboardWillHideNotification                                           object:nil];创建一个全局变量以跟踪当前的键盘高度:CGFloat _currentKeyboardHeight = 0.0f;实现keyboardWillShow以对键盘高度的当前变化做出反应:- (void)keyboardWillShow:(NSNotification*)notification {   NSDictionary *info = [notification userInfo];   CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;   CGFloat deltaHeight = kbSize.height - _currentKeyboardHeight;    // Write code to adjust views accordingly using deltaHeight   _currentKeyboardHeight = kbSize.height;}注意:您可能希望为视图的偏移设置动画。该信息字典包含键的值UIKeyboardAnimationDurationUserInfoKey。此值可用于以与显示键盘相同的速度为更改设置动画。将keyboardWillHide实现为reset _currentKeyboardHeight并对被关闭的键盘做出反应:- (void)keyboardWillHide:(NSNotification*)notification {   NSDictionary *info = [notification userInfo];   CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;   // Write code to adjust views accordingly using kbSize.height   _currentKeyboardHeight = 0.0f;}

蝴蝶不菲

在遇到这篇StackOverflow文章之前,我也遇到了这个问题:转换UIKeyboardFrameEndUserInfoKey这将向您展示如何使用该convertRect功能,将键盘的大小转换为可用的大小,但要以屏幕方向为准。NSDictionary* d = [notification userInfo];CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];r = [myView convertRect:r fromView:nil];以前,我有一个iPad应用程序可以使用UIKeyboardFrameEndUserInfoKey但不使用convertRect,并且运行良好。但是在iOS 8上,它不再能正常工作。突然,它报告说我的键盘在横向模式下的iPad上运行,高度为1024像素。因此,现在,在iOS 8上,必须使用此convertRect功能。
打开App,查看更多内容
随时随地看视频慕课网APP