在运行时更改约束



我目前正在Swift中使用UIKit制作一个消息应用程序。因此,我显然需要能够显示和隐藏键盘。事实上,展示和隐藏它本身并不是问题。

然而,一个挑战是,当键盘显示/隐藏时,仅将某些视图移动一定的量。我有一种方法可以掌握键盘的高度,所以在这里获得正确的数字不是一个挑战。

我正在努力改变这个观点。我在屏幕底部有一个UIView,里面有一个文本字段和按钮,当键盘出现时,我希望它向上移动。问题是视图设置了约束,当我试图删除或重新定义这些约束时,控制台中会出现很多错误。

我尝试过bottomView.removeConstraints(bottomView.constraints),然后重新定义了所有这些,我尝试过bottomView.bottomAnchor.constraint(view.bottomAnchor).isActive = false,然后激活了另一个,但我怀疑我不了解这些程序约束是如何工作的。我已经看到其他几个Stack Overflow答案提到了"bottomView.constant"或"bottomView.bottomAnchor.constant",但似乎视图及其约束/锚都没有这样的属性。

问题:即使UIView已经设置了约束,当iOS键盘出现时,我如何将UIView移动固定距离?

感谢所有的帮助。

您可以使用IQKeyboardManager。这很简单。https://github.com/hackiftekhar/IQKeyboardManager

或者你可以按照下面的代码

class ViewController: UIViewController {
@IBOutlet weak var textFieldBottomConstraint: NSLayoutConstraint!

override func viewDidLoad() {
super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(notification:)), name:  UIResponder.keyboardWillShowNotification, object: nil )
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillShow( notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
var newHeight: CGFloat
let duration:TimeInterval = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
if #available(iOS 11.0, *) {
newHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
newHeight = keyboardFrame.cgRectValue.height
}
let keyboardHeight = newHeight  + 16
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: {
self.textFieldBottomConstraint.constant = -keyboardHeight
self.view.layoutIfNeeded() },
completion: nil)
}
}
}

最新更新