ios - iPad 上的键盘高度不正确

标签 ios swift

我有一个 UIView 固定在我的 superview 的底部。它有一个 TextView ,点击后将成为第一响应者。此时,我检测到键盘将显示并更改其底部约束以将其向上移动,使其位于键盘上方。我使用以下代码来执行此操作:

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 转换文档中所述)。

如果您避免所有 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()
    }
}

关于ios - iPad 上的键盘高度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54238957/

相关文章:

ios - 问答 - 如何强制设备方向在横向和纵向之间旋转

android - Paypal 与 Ionic 框架的集成不起作用

ios - 如何检索某些 childByAutoId() 键

ios - 单击屏幕左边缘的按钮时不突出显示,但触发事件

ios - Swift 是 UIImage 类实习

ios - 是否可以将 SwiftUI 列表项文本选择性地设置为常见问题解答部分的粗体?

xcode - 'AnyObject' 没有名为 'group' 的成员

iOS swift : init not being fired?

ios - 如何更改现有 UIAlertAction 的标题?

ios - 为什么在呈现新的 View Controller 后标签栏丢失?