Where to update Autolayout constraints when size changes?

前端 未结 2 479
庸人自扰
庸人自扰 2020-12-19 03:58

I have several UIViews laid out along the bottom of a containing UIView. I want these views to always be equal width, and always stretch to collect

相关标签:
2条回答
  • 2020-12-19 04:24

    On all classes that implement the UITraitEnvironment protocol the method traitCollectionDidChange will be called when the trait collection changes, like on rotation. This is the appropiate place to manually update the constraints when using the new Size Classes. You can also animate the transition with the method willTransitionToTraitCollection

    Basic example:

    class ViewController: UIViewController {
    
      var constraints = [NSLayoutConstraint]()
    
      func updateConstraintsWithTraitCollection(traitCollection: UITraitCollection) {
        // Remove old constraints
        view.removeConstraints(constraints)
    
        // Create new constraints
      }
    
      override func willTransitionToTraitCollection(newCollection: UITraitCollection!,
        withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator!) {
    
          super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
    
          coordinator.animateAlongsideTransition({ (context: UIViewControllerTransitionCoordinatorContext!) in
            self.updateConstraintsWithTraitCollection(newCollection)
            self.view.setNeedsLayout()
          }, completion: nil)
    
      }
    
      override func traitCollectionDidChange(previousTraitCollection: UITraitCollection!) {
        updateConstraintsWithTraitCollection(traitCollection)
      }
    }
    

    Besides that I want to recommend Cartography, which is a nice library that helps to make auto layout more readable and enjoyable. https://github.com/robb/Cartography

    0 讨论(0)
  • 2020-12-19 04:34

    There is no reason to update the width manually:

    1. Place all the views with equal width in your view with no spacing in between each other
    2. Add an equal width constraint to all of them
    3. Add constraints with 0 width for spacing between sides and each other
    4. Lower the priority of one or more of the equal width constraints just in case the width cannot be divided equally.

    Then auto layout will handle everything for you.

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