如何通过iOS获得UIKeyboard尺寸

Tha*_*nka 66 iphone objective-c soft-keyboard ios

有没有办法以编程方式获得UIKeyboard大小.高度216.0f,景观高度162.0f.

以下似乎已被弃用.有没有什么方法可以在3.0 iPhone OS SDK和4.0 iPhone OS SDK中都没有任何警告来执行此操作.

CGSize keyBoardSize = [[[note userInfo]
                        objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
Run Code Online (Sandbox Code Playgroud)

Jam*_*ord 141

您可以userInfo使用UIKeyboardFrameBeginUserInfoKeyUIKeyboardFrameEndUserInfoKey从字典中获取键盘大小.

这两个键返回一个NSValue实例,其中包含CGRect键盘在显示/隐藏动画的起点和终点的位置和大小.

编辑:

为了澄清,userInfo字典来自NSNotification实例.它传递给您向观察者注册的方法.例如,

- (void)someMethodWhereYouSetUpYourObserver
{
    // This could be in an init method.
    [[NSNotificationCenter defaultCenter] addObserver:self 
                    selector:@selector(myNotificationMethod:) 
                    name:UIKeyboardDidShowNotification 
                    object:nil];
}

- (void)myNotificationMethod:(NSNotification*)notification
{
    NSDictionary* keyboardInfo = [notification userInfo];
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}
Run Code Online (Sandbox Code Playgroud)

编辑2:

此外,请不要忘记在您的dealloc方法中删除自己作为观察者!这是为了避免通知中心在释放后通知您的对象时发生的崩溃.

  • 在用户隐藏/显示QuickType建议的情况下,最好使用UIKeyboardFrameEndUserInfoKey来确定键盘的结束高度.要隐藏/显示QuickType建议,请向上滑动或向下滑动键盘上方的建议.如果您使用UIKeyboardFrameBeginUserInfoKey而不是UIKeyboardFrameEndUserInfoKey,键盘的高度将不正确 (9认同)
  • 别忘了: - (void)dealloc {[[NSNotificationCenter defaultCenter] removeObserver:self]; } (3认同)
  • 没问题!刚刚编辑了我的答案 - 这有帮助吗? (2认同)

Jef*_*Sun 47

您应该使用UIKeyboardWillChangeFrameNotification相反的,因为一些国际键盘,如中文键盘,将在使用过程中更改帧.还要确保将其CGRect转换为适当的视图,以供横向使用.

//some method like viewDidLoad, where you set up your observer.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

- (void)keyboardWillChange:(NSNotification *)notification {
    CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; //this is it!
}
Run Code Online (Sandbox Code Playgroud)

  • +1为一个很好的答案.非常有用也适用于iOS 8中的第三方键盘 (3认同)