【问题标题】:Keyboard height incorrect on iPadiPad 上的键盘高度不正确
【发布时间】:2019-01-17 15:17:24
【问题描述】:

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

【问题讨论】:

  • 请显示转换功能
  • @Scriptable 转换函数是苹果自己的:developer.apple.com/documentation/uikit/uicoordinatespace/…
  • 啊!我不知道这种方法。我显然从来没有使用过它,但也从来没有需要,我通常用键盘向上移动我的视图。
  • func convert(_ point: CGPoint, from view: UIView?) -> CGPoint . 将一个点从给定视图的坐标系转换为接收者的坐标系。

标签: ios swift


【解决方案1】:

在转换键盘的框架时,您应该将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()
    }
}

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 2015-01-04
    • 1970-01-01
    • 2016-07-08
    • 2011-10-29
    • 1970-01-01
    • 2011-05-11
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多