在设备轮换时保持autolayout约束活动状态

Sal*_*lah 3 ios autolayout

我注意到,当我以编程方式更新自动布局约束时,在旋转屏幕时会恢复所有更改.

重现问题:

  • 带有UIView的基本Storyboard界面和2个约束:

    1. width等于superview.width(乘数1)有效
    2. 宽度等于superview.width(乘数1/2)禁用
  • 使用IBOutlet创建并链接这两个约束

  • 以编程方式禁用第一个约束并启用第二个约束.
  • 旋转设备,第一个约束处于活动状态,第二个约束处于禁用状态.

对我来说似乎是一个错误.

你怎么看 ?

截图:

故事板: 在此输入图像描述

约束#1:

在此输入图像描述

约束#2:

在此输入图像描述

Swi*_*ect 7

大小类

已安装是指安装大小类,而不是活动/非活动.

您必须以编程方式创建另一个约束,并激活/停用约束.这是因为您无法更改约束的乘数(我可以更改NSLayoutConstraint的乘数属性吗?),也不能修改大小类(activateConstraints:和deactivateConstraints:在IB中创建的约束后不会保持旋转).

有几种方法可以做到这一点.在下面的示例中,我使用乘数或1/2创建x1约束的副本.然后我在两者之间切换:

@IBOutlet var fullWidthConstraint: NSLayoutConstraint!
var halfWidthConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    halfWidthConstraint = NSLayoutConstraint(item: fullWidthConstraint.firstItem,
        attribute: fullWidthConstraint.firstAttribute,
        relatedBy: fullWidthConstraint.relation,
        toItem: fullWidthConstraint.secondItem,
        attribute: fullWidthConstraint.secondAttribute,
        multiplier: 0.5,
        constant: fullWidthConstraint.constant)
    halfWidthConstraint.priority = fullWidthConstraint.priority
}

@IBAction func changeConstraintAction(sender: UISwitch) {
    if sender.on {
        NSLayoutConstraint.deactivateConstraints([fullWidthConstraint])
        NSLayoutConstraint.activateConstraints([halfWidthConstraint])
    } else {
        NSLayoutConstraint.deactivateConstraints([halfWidthConstraint])
        NSLayoutConstraint.activateConstraints([fullWidthConstraint])
    }
}
Run Code Online (Sandbox Code Playgroud)

iOS 9+,Xcode 7+上测试过.