我在视图的底部有一个文本输入字段,我试图上下对其进行动画处理以保持在键盘上方。
func setupKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillChangeFrame), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func handleKeyboardWillChangeFrame(notification: NSNotification) {
let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let keyboardDuration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double)
print(keyboardFrame)
orderDetailView?.textInputViewBottomAnchor?.constant = -keyboardFrame!.height
UIView.animate(withDuration: keyboardDuration!) {
self.view.layoutIfNeeded()
}
}
OrderDetailView是视图控制器的视图。
textinputview是动画的一部分,当第一次显示键盘时它可以正常工作,但是当我发送消息并且键盘退出第一响应者时也不能进行动画处理,也不能通过在键盘外部单击来退出firstresponder。
当我从keyboardFrameEndUserInfoKey打印cgrect值时,它将返回与存在键盘时相同的帧值(而不是0)。
当我从视图中向下拖动键盘时,这似乎只能正常工作。
谢谢你的帮助。
最佳答案
在您的情况下,当键盘隐藏时,高度仍不为零,我认为这是您的问题。您需要根据需要将键盘框架转换为视图坐标系并设置约束。检查以下内容:
@objc private func onKeyboardChange(notification: NSNotification) {
guard let info = notification.userInfo else { return }
guard let value: NSValue = info[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
let newFrame = value.cgRectValue
if let durationNumber = info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let keyboardCurveNumber = info[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
let duration = durationNumber.doubleValue
let keyboardCurve = keyboardCurveNumber.uintValue
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(rawValue: keyboardCurve), animations: {
self.updateFromKeyboardChangeToFrame(newFrame)
}, completion: { _ in
// After animation
})
} else {
self.updateFromKeyboardChangeToFrame(newFrame)
}
}
private func updateFromKeyboardChangeToFrame(_ keyboardFrame: CGRect) {
let view: UIView! // Whatever view that uses bottom constraint
let bottomConstraint: NSLayoutConstraint! // Your bottom constraint
let constant = view.bounds.height-max(0, view.convert(keyboardFrame, from: nil).origin.y)
bottomConstraint.constant = max(0, constant)
view.layoutIfNeeded()
}
在您的情况下,您似乎使用
let view = self.view
let bottomConstraint = orderDetailView?.textInputViewBottomAnchor
这取决于您如何定义约束,但似乎您需要将负值用作
bottomConstraint.constant = -max(0, constant)
。关于ios - keyboardFrameEndUserInfoKey没有显示正确的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52825706/