gpt4 book ai didi

swift - heightAnchor.constraint 不改变 View 高度

转载 作者:行者123 更新时间:2023-11-28 09:48:52 31 4
gpt4 key购买 nike

我使用这段代码:

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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com