在textFieldShouldBeginEditing委托中获取键盘大小

时间:2015-09-22 05:30:02

标签: ios iphone uikeyboard

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

中获得总大小和框架
  

textFieldShouldBeginEditing

委托。

3 个答案:

答案 0 :(得分:7)

您应该使用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
}

答案 1 :(得分:4)

注册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];
}

答案 2 :(得分:4)

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

//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;
}