gpt4 book ai didi

ios - Swift:自动布局约束问题。人像与风景

转载 作者:行者123 更新时间:2023-11-28 14:36:55 30 4
gpt4 key购买 nike

我遇到了基于屏幕方向的自动布局约束问题。为了实现约束,我使用 Autolayout anchor ,重写 traitCollectionDidChange 方法并创建两个我设置约束的函数。类似的东西:

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)

switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {

case (.compact, .compact):
print("compact-compact")
setupLandscapeLayout()

case (.compact, .regular):
print("compact-regular")
setupPortraitLayout()

default: break
}
}

private func setupPortraitLayout() {
myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

}

private func setupLandscapeLayout() {
myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 20).isActive = true
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = false

}

所以这里的问题是在方向改变期间只工作一次的约束。每次下一次尝试都不起作用。我还尝试使用 view.layoutIfNeeded() 但没有用。甚至尝试设置 isActive=false 并创建一个新的约束 - 也没有成功(

那么是否可以按照我的方式设置约束,或者有另一种更好的方法如何以编程方式更新屏幕方向的约束?

最佳答案

目前您正在复制约束,这会导致冲突将这两个约束放在 viewDidLoad 中(根据当前方向将 bot 设置为 20 或 -20)

botCon =  myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20)
botCon.isActive = true
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

//

private func setupPortraitLayout() {                
self.botCon.constant = -20
self.view.layoutIfNeeded()
}
private func setupLandscapeLayout() {
self.botCon.constant = 20
self.view.layoutIfNeeded()
}

关于ios - Swift:自动布局约束问题。人像与风景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50824597/

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