我有一个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上,它似乎可以移动两倍的高度。为什么会这样?
答案 0 :(得分:0)
转换键盘框架时,应将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()
}
}