在iPhone / iPad上自动旋转后将引脚更新到键盘

时间:2015-10-09 15:25:33

标签: ios keyboard autolayout auto-rotation

我有工作代码,当UI出现时会将UI固定到键盘高度:

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.bottomSpacing.constant = kbSize.height + 10;
    [self.view layoutIfNeeded];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    self.bottomSpacing.constant = 10;
    [self.view layoutIfNeeded];
}

但是当设备自动旋转时出现问题:键盘高度变化(例如iPad 313 => 398)和' bottomSpacing'变得过时了。

如何将其更新为新的键盘高度?或者,是否可以将自动布局约束分配给键盘视图?

1 个答案:

答案 0 :(得分:0)

最简单的方法是收听UIKeyboardWillChangeFrameNotification通知:

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

...

- (void)keyboardWillResize:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    float keyboardTop = CGRectGetMinY([info[UIKeyboardFrameEndUserInfoKey] CGRectValue]);
    float animationDuration = info[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    [self.view layoutIfNeeded];
    [UIView animateWithDuration:animationDuration animations:^{
        self.pinToKeyboardConstraint.constant = keyboardTop;
        [self.view layoutIfNeeded];
    }];
}

只要键盘更改了界限,包括显示和隐藏事件,就会触发此通知。