ios - iPad 上的键盘高度不正确
问题描述
我UIView
的superview
. 这有一个文本视图,在点击时会成为第一响应者。此时,我检测到键盘将显示并更改其底部约束以将其向上移动,使其位于键盘上方。我使用以下代码来执行此操作:
private func keyboardWillShow(_ aNotification: Notification) {
guard let info = (aNotification as NSNotification).userInfo,
let endFrame = (info as NSDictionary).value(forKey: UIResponder.keyboardFrameEndUserInfoKey),
let currentKeyboard = (endFrame as AnyObject).cgRectValue,
let rate = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber
else { return }
let convertedFrame = self.view.convert(currentKeyboard, from: UIScreen.main.coordinateSpace)
bottomConstraint.constant = self.view.frame.height - convertedFrame.origin.y
UIView.animate(withDuration: rate.doubleValue) {
self.view.layoutIfNeeded()
}
}
这在 iPhone 上运行良好。然而,在 iPad 上,它似乎向上移动了两倍的高度。为什么是这样?
解决方案
转换键盘的框架时,您应该传递nil
给from
参数。从窗口坐标正确转换(如UIView convert
文档中所述)。
如果您避免使用所有的 Objective-C 编码,您的代码也会更简单。
private func keyboardWillShow(_ aNotification: Notification) {
guard let info = aNotification.userInfo,
let endFrame = info[UIWindow.keyboardFrameEndUserInfoKey] as? NSValue,
let rate = info[UIWindow.keyboardAnimationDurationUserInfoKey] as? NSNumber
else { return }
let currentKeyboard = endFrame.cgRectValue
let convertedFrame = self.view.convert(currentKeyboard, from: nil)
bottomConstraint.constant = self.view.frame.height - convertedFrame.origin.y
UIView.animate(withDuration: rate.doubleValue) {
self.view.layoutIfNeeded()
}
}
推荐阅读
- azure-ad-b2c - 删除 AD B2C 租户 Powershell
- android - 来自 AutoCompleteTextView 的 GetSelectedItem/值 [不工作]
- c++ - 使用大括号进行结构初始化
- c++ - Qt:如何从应用程序的资源中打开 pdf 文件?
- node.js - React、node js、mongoDB - 如何使用 FormData 进行发布、放置、删除?
- python-3.x - 将远程 linux 系统时间同步到本地 windows 笔记本电脑
- java - 如何使多边形附加到 3 点钟位置的点
- r - 将第一个非缺失值存储在新列中
- node.js - NodeJS+Express循环调用异步方法
- python - PySFTP 和 get_r 使用 Python - “没有这样的文件或目录”