iPhone/iPad 自转后更新键盘引脚

Update pin to keyboard after autorotation on iPhone/iPad

我有工作代码,当 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' 变得过时。

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

最简单的方法是收听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];
    }];
}

每当键盘更改边界(包括显示和隐藏事件)时都会触发此通知。