Keep autolayout constraints active status on device rotation

后端 未结 3 1775
挽巷
挽巷 2021-01-21 10:00

I noticed that when I update my autolayout constraints programmatically, all changes are reverted when I rotate the screen.

Reproduce the issue:

  • Basic S

3条回答
  •  借酒劲吻你
    2021-01-21 11:00

    Size Classes

    Installed refers to Size Classes installation, not to active/inactive.

    You must create another constraint programmatically, and activate/deactivate that one. This is because you cannot change the multiplier of a constraint (Can i change multiplier property for NSLayoutConstraint?), nor can you tinker with Size Classes (activateConstraints: and deactivateConstraints: not persisting after rotation for constraints created in IB).

    There are a few ways to do so. In the example below, I create a copy of your x1 constraint, with a multiplier or 1/2. I then toggle between the two:

    @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])
        }
    }
    

    Tested on iOS 9+, Xcode 7+.

提交回复
热议问题