在textFieldShouldBeginEditing委托中获取键盘大小

MUH*_*SIM 1 iphone uikeyboard ios

我正在创建一个消息传递应用程序时遇到问题,当键盘打开时,我不确定键盘的总大小和框架(字典区域是否打开).我希望得到总大小和框架

textFieldShouldBeginEditing

代表.

小智 7

您应该使用UIKeyboardWillChangeFrameNotification.还要确保将CGRect转换为适当的视图,以供横向使用.

在您的.中设置NSNotificationCenter textFieldShouldBeginEditing

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

并写这个方法.

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

在Swift 4中

 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_noti:) ), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)
Run Code Online (Sandbox Code Playgroud)

KeyboardWillChange方法

@objc func keyboardWillChange(_noti:NSNotification)
{
    let keyBoard = _noti.userInfo
    let keyBoardValue = keyBoard![UIKeyboardFrameEndUserInfoKey]
    let fram = keyBoardValue as? CGRect // this is frame
}
Run Code Online (Sandbox Code Playgroud)