我使用下面的代码来获得键盘高度.然后使用此高度计算a的框架,UIView以确保它UIView位于键盘顶部.
但在iPhoneX模拟器中,输出是333和iPhone 8模拟器一样258.
问题:如果rect.height用作iPhone 8模拟器的键盘高度,那么布局是正确的.对于iPhone X而言,它UIView与键盘之间存在差距.这意味着333高于iPhone X中的真实键盘高度.
高度的原因是什么?以及如何获得正确的键盘高度?
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
@objc func keyboardWillShow(_ notification: NSNotification) {
if let rect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
print(rect.height)
}
}
Run Code Online (Sandbox Code Playgroud)
像这张图片一样,绿色边框应该是额外的部分.实际上,我需要键盘顶部的红色部分没有绿色矩形间隙.

编辑
好的,在@ Craig的帮助下,我发现这个方法只能由iPhone X调用.所以我在这里更新框架.只需在此处粘贴代码即可.
安全区底部高度为22.0似乎不正确.
override func viewSafeAreaInsetsDidChange() {
if #available(iOS 11.0, *) {
super.viewSafeAreaInsetsDidChange()
view.safeAreaInsets.bottom // This value is the bottom safe area place value.
}
}
Run Code Online (Sandbox Code Playgroud)
EDIT2
通常view.safeAreaInsets.bottom应该是34.0,但是如果你使用容器视图,这个值可能会有所不同,就像我的22.0.
Kqt*_*qtr 43
虽然Craig的答案是正确的,但您可能不希望将视图固定到 view.bottom或bottomLayoutGuide而不是安全区域底部(特别是如果您的键盘并不总是打开,并且您不希望您的视图覆盖Home Indicator区域).
以下是针对这些案例的修复方法.它从键盘的高度减去安全区域底部插入的高度:
var keyboardHeight = ... // Get the keyboard height from keyboard notification
if #available(iOS 11.0, *) {
let bottomInset = view.safeAreaInsets.bottom
keyboardHeight -= bottomInset
}
Run Code Online (Sandbox Code Playgroud)
Cra*_*itt 34
iPhone X和iPhone 8的键盘高度应该是正确的.我只能猜测你的代码中可能存在定位"红色部分"的问题,你的假设是键盘高度不正确,而问题实际上是在视图的位置.现在 - 位置问题的原因?我的第二个猜测是红色部分固定在底部安全区域布局指南,其中iPhone 8为0,但在iPhone X上嵌入了34个点.
看到此图像以示出两个在键盘的高度,有可能使用来自在所报告的键盘高度键盘高度来绘制矩形键盘上方的差NSNotification为keyboardWillShow方法:
如果你想分享你的代码/约束来定位红色视图,我应该能够向你展示问题.
- 编辑:对于有兴趣知道如何提取红色矩形的人,我会在博客文章[这里]进入.(https://craiggrummitt.com/2019/02/22/getting-the-keyboard - 高度/).
到目前为止,这适用于所有设备和 iOS 版本
- (void)keyboardWillShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGFloat kbHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
CGFloat safeAreaBottomInset = 0;
if (@available(iOS 11.0, *)) {
safeAreaBottomInset = self.view.safeAreaInsets.bottom;
}
self.containerViewBottomConstraint.constant += (kbHeight - safeAreaBottomInset); //In my case I use a constraint to adapt the UI when the keyboard is presented
[self.view layoutIfNeeded];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13308 次 |
| 最近记录: |