在 textFieldShouldBeginEditing 委托中获取键盘大小

Get Keyboard size in textFieldShouldBeginEditing delegate

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

中获得总尺寸和框架

textFieldShouldBeginEditing

代表。

注册 UIKeyboardWillShowNotification。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

并在选择器中获取键盘框架:

- (void)keyboardWillShow:(NSNotification *)iNotification {
    NSDictionary *userInfo = [iNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
}

您应该使用 UIKeyboardWillChangeFrameNotification 。还要确保将 CGRect 转换为正确的视图,以便横向使用。

textFieldShouldBeginEditing

中设置 NSNotificationCenter
[[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!
}

在Swift 4

 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_noti:) ), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)

KeyboardWillChange 方法

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

我遇到过这个问题并通过使用键盘上的通知观察器解决了。

//set observer in textFieldShouldBeginEditing like    
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myNotificationMethod:) name:UIKeyboardWillChangeFrameNotification object:nil];
    return YES;
}

// method implementation
- (void)myNotificationMethod:(NSNotification*)notification
{
    NSDictionary* keyboardInfo = [notification userInfo];
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
    NSLog(@"%@",keyboardFrameBegin);

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

//remove observer
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
   [[NSNotificationCenter defaultCenter ]removeObserver:self];    
    return YES;
}