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

2023-12-02

iOS 9 添加了一个快捷栏到 iOS 8QuickType 栏.

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

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

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

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

期望的行为:

enter image description here
(Notice how the red view is attached to the top of the keyboard)

实际行为:

enter image description here

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


问题是大多数代码(包括苹果公司)忽略了这样一个事实UIKeyboardFrameEndUserInfoKey is a 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)正在使用中。矩形的起源很重要,不应被忽视。

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

enter image description here

当键盘处于仅限快捷栏模式时,这是矩形:

enter image description here

请注意,键盘的大部分位于屏幕外,但高度仍然相同。

要获得正确的行为,请使用CG矩形交集视图的边界和该视图内的键盘框架:

// ✅ 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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐