Swift:Autolayout约束问题。肖像与景观

时间:2018-06-12 19:36:07

标签: ios swift

我一直坚持基于屏幕方向的Autolayout约束问题。为了实现约束,我使用Autolayout锚点,覆盖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并创建一个新约束 - 也没有成功(

那么有可能以我的方式设置约束,还是有另一种更好的方法来如何以编程方式更新屏幕方向的约束?

1 个答案:

答案 0 :(得分:1)

目前您正在重复约束,这就产生了冲突 将这两个约束放在viewDidLoad中(根据当前方向将机器人设置为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()
}