对象 - 返回错误的键盘高度?

时间:2017-12-12 03:17:49

标签: ios objective-c

我试图获得iOS键盘的高度,以便在键盘动画时我可以移动我的视图。但是,我一直得到返回值258(这是不正确的,因为它推动我的视图太高了?)为什么会发生这种情况?代码如下:

ViewController.m

-(void)viewDidLoad {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

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

        NSDictionary* keyboardInfo = [notification userInfo];

        NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];

        CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
      self.keyboardHeight = keyboardFrameBeginRect.size.height;


    }

    - (void) animateTextView:(BOOL) up
    {

        const int movementDistance = self.keyboardHeight;

        const float movementDuration = 0.3f;
        int movement= movement = (up ? -movementDistance : movementDistance);


        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];

        self.upView.frame = CGRectOffset(self.upView.frame, 0, movement);
        [UIView setAnimationDidStopSelector:@selector(afterAnimationStops)];
        [UIView commitAnimations];

    }

2 个答案:

答案 0 :(得分:1)

要获得键盘高度,您应使用UIKeyboardWillShowNotificationUIKeyboardDidShowNotification代替UIKeyboardWillChangeFrameNotification.

-(void)viewDidLoad {

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

}

如果使用UITabBarController,则必须在没有标签栏高度的情况下计算框架。您可以使用下面的代码获得标签栏高度。

self.tabBarController.tabBar.frame.height

答案 1 :(得分:0)

您应该注册UIKeyboardWillShowNotification以观察键盘高度。

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

2)你也可以试试这段代码:

(void)keyboardWillChange:(NSNotification *)notification 
{
    NSDictionary* keyboardInfo = [notification userInfo];
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}