Keep autolayout constraints active status on device rotation

后端 未结 3 1773
挽巷
挽巷 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 10:45

    You can do the necessary switch with the constraints created via IB for size classes. The trick is to keep the collapsed state in a variable and update constraints as on your button's event as also on trait collection change event.

    var collapsed: Bool {
        didSet {
            view.setNeedsUpdateConstraints()
        }
    }
    
    @IBAction func onButtonClick(sender: UISwitch) {
        view.layoutIfNeeded()
        collapsed = !collapsed        
        UIView.animate(withDuration: 0.3) {
            view.layoutIfNeeded()
        }
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        view.setNeedsUpdateConstraints()
    }
    
    override func updateViewConstraints() {
        constraint1.isActive = !collapsed
        constraint2.isActive = collapsed
        super.updateViewConstraints()
    }
    
    0 讨论(0)
  • 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+.

    0 讨论(0)
  • 2021-01-21 11:05

    I will describe how to simple switch between the two layouts.

    When the screen rotates, Autolayout apply the installed default layout with the higher priority. It does not matter whether Constraint is Active or not. Because, when rotating, the high priority layout on the storyboard is reinstalled and active = true. Therefore, even if you change active, the default layout is applied when you rotate and you can not keep any layout.

    Instead of switching active state, switching two layouts. When switching between two layouts, use "priority" rather than "active". This way does not need to worry about the state of active. It's very simple.

    First, create two layouts to switch, on Storyboard. Check both for Installed. A conflict error occurs because two layouts have priority = 1000 (required). Set the priority of the layout to be displayed first to High. And the priority of the other layout is set to Low, conflict error will be resolved. Associate constraints of those layouts as IBOutlet of class. Finally, just switch the priority between high and low at the timing you want to change the layout. Note, please do not change priority to "required". Layout with priority set to required can not be changed it after that.

    class RootViewController: UIViewController {
    
        @IBOutlet var widthEqualToSuperView: NSLayoutConstraint!
        @IBOutlet var halfWidthOfSuperview: NSLayoutConstraint!
    
        override func viewDidLayoutSubviews() {
            changeWidth()
        }
    
        func changeWidth() {
            let orientation = UIApplication.shared.statusBarOrientation
            if (orientation == .portrait || orientation == .portraitUpsideDown) {
                widthEqualToSuperView.priority = UILayoutPriorityDefaultHigh;
                halfWidthOfSuperview.priority = UILayoutPriorityDefaultLow;
            }
            else {
                widthEqualToSuperView.priority = UILayoutPriorityDefaultLow;
                halfWidthOfSuperview.priority = UILayoutPriorityDefaultHigh;
            }
        }
    
    }
    

    portrait with full width landscape with half width

    0 讨论(0)
提交回复
热议问题