OGeek|极客世界-中国程序员成长平台

标题: iOS swift : Constraints did not update on screen [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:13
标题: iOS swift : Constraints did not update on screen

晚上,

我遇到了 ScrollView 约束的问题。

这是我的代码:

// when the keyboard is shown, move up some elements
    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

            // Bring up the scrol lview
            print(scrollViewBottomConstraint.constant)
            self.scrollViewBottomConstraint.constant = keyboardSize.height
            print(scrollViewBottomConstraint.constant)
            self.view.updateConstraints()
            self.view.updateConstraintsIfNeeded()
            self.view.needsUpdateConstraints()
            self.view.layoutIfNeeded()

            // Bring up the next arrow with animation
            self.nextButtonBottomConstraint.constant = keyboardSize.height + 8
            UIView.animate(
                withDuration: 1.0,
                delay: 0.0,
                usingSpringWithDamping: 0.5,
                initialSpringVelocity: 6.0,
                options: [.allowUserInteraction,
                          .curveEaseInOut],
                animations: {
                    self.view.layoutIfNeeded()
            }, completion: nil)
        }
    }

控制台打印 0 和 253,因此约束常量被更新。但在屏幕上我看不到变化,我有这个日志:

[Snapshotting] Snapshotting a view (0x7fa041471bc0, UIInputSetHostView) that has not been rendered at least once requires afterScreenUpdates:YES.



Best Answer-推荐答案


很奇怪,更改约束后只需 view.layoutIfNeeded() 就可以了。

尝试删除:

self.view.updateConstraints()
self.view.updateConstraintsIfNeeded()
self.view.needsUpdateConstraints()

只是:

 view.layoutIfNeeded()

试试这个:

@objc func keyboardWillShow(notification: NSNotification) {
    guard let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else{
       return
    }

    scrollViewBottomConstraint.constant = keyboardSize.height
    nextButtonBottomConstraint.constant = keyboardSize.height + 8
    view.layoutIfNeeded()
}

关于iOS swift : Constraints did not update on screen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47157215/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4