在 iOS 9 仅快捷栏模式下,与键盘顶部对齐的视图出现在错误的位置

View aligned to top of keyboard appears in wrong place in iOS 9 Shortcut Bar only mode

iOS 9 加一个Shortcut Bar to the iOS 8 QuickType bar.

作为此更改的一部分,如果将​​蓝牙键盘连接到 iPad,键盘将处于仅最小化快捷方式栏模式(可以通过在模拟器中按 command-k 来模拟)。

我有使用类似于以下方法获取键盘高度的代码:

CGRect keyboardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat keyboardHeight = keyboardFrame.size.height; // = 313

问题是当键盘在展开和折叠状态之间切换时,高度保持不变,导致我的视​​图出现在原来的位置:

期望的行为:


(Notice how the red view is attached to the top of the keyboard)

实际行为:

将红色视图附加到键盘顶部的正确方法是什么?

问题是大多数代码(including Apple 的)忽略了 UIKeyboardFrameEndUserInfoKey 是一个 CGRect 并且不是 CGSize

// ❌ Bad code, do not use
- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = activeField.superview.frame;
    bkgndRect.size.height += kbSize.height;
    [activeField.superview setFrame:bkgndRect];
    [scrollView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height) animated:YES];
}

在这里您看到仅使用了键盘高度 (kbSize.height)。 rect的原点很重要,不容忽视。

当键盘可见时,这是报告的矩形:

当键盘处于仅快捷方式栏模式时,这是 rect:

注意键盘的大部分是如何在屏幕外的,但它的高度仍然相同。

要获得正确的行为,请将 CGRectIntersection 与视图的边界和该视图中的键盘框架一起使用:

// ✅ Good code, use
CGRect keyboardScreenEndFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect keyboardViewEndFrame = [self.view convertRect:keyboardScreenEndFrame fromView:self.view.window];
CGRect keyboardFrame = CGRectIntersection(self.view.bounds, keyboardViewEndFrame);
CGFloat keyboardHeight = keyboardFrame.size.height; // = 55

出于同样的原因,应该使用 UIKeyboardFrameEndUserInfoKey 而不是 UIKeyboardFrameBeginUserInfoKey