首页 > 解决方案 > iPad 上的键盘高度不正确

问题描述

UIViewsuperview. 这有一个文本视图,在点击时会成为第一响应者。此时,我检测到键盘将显示并更改其底部约束以将其向上移动,使其位于键盘上方。我使用以下代码来执行此操作:

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 上,它似乎向上移动了两倍的高度。为什么是这样?

标签: iosswift

解决方案


转换键盘的框架时,您应该传递nilfrom参数。从窗口坐标正确转换(如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()
    }
}

推荐阅读