Keep autolayout constraints active status on device rotation

后端 未结 3 1797
挽巷
挽巷 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条回答
  •  萌比男神i
    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()
    }
    

提交回复
热议问题