我使用这个代码:

func show(){
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    view.heightAnchor.constraint(equalToConstant: view.frame.height - 300).isActive = true
    view.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
}

func hide(){
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    view.heightAnchor.constraint(equalToConstant: view.frame.height + 300).isActive = true
    view.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
}

show函数工作正常,但hide函数不工作,heightAnchor不工作。

最佳答案

先声明约束

var heightArchonWhenShow = view.heightAnchor.constraint(equalToConstant: view.frame.height - 300)
var heightArchonWhenHide = view.heightAnchor.constraint(equalToConstant: view.frame.height + 300)

初始化ViewDidLoad上的约束后
func setConstraints(){
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    view.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
    heightArchonWhenShow.isActive = true
}

简单的激活它们,不要覆盖。这样地:
func show(){
    heightArchonWhenShow.isActive = true
    heightArchonWhenHide.isActive = false
}

func hide(){
    heightArchonWhenShow.isActive = false
    heightArchonWhenHide.isActive = true
}

如果你想你也可以动画的变化,如:
func hide(){
    heightArchonWhenShow.isActive = false
    heightArchonWhenHide.isActive = true

    UIView.animate(withDuration: 0.3) {
        self.view.layoutIfNeeded()
    }
}

关于swift - heightAnchor.constraint不会更改 View 高度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53739783/

10-09 20:42