在运行时更改约束

时间:2020-08-08 00:29:54

标签: swift uiview constraints

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

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

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

我尝试了bottomView.removeConstraints(bottomView.constraints),然后重新定义了所有参数,尝试了bottomView.bottomAnchor.constraint(view.bottomAnchor).isActive = false,然后激活了另一个参数,但是我怀疑我对这些程序约束的工作原理缺乏了解。我还看到了其他一些有关“ bottomView.constant”或“ bottomView.bottomAnchor.constant”的Stack Overflow答案,但似乎视图及其约束/锚都没有这样的属性。

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

感谢所有帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用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)
        }
    }
}