The Layout Engine in Swift

Many iOS developers do not think about how the mechanism for rendering elements, setting and updating constraints in Auto Layout'e works. In this article, I try to look in detail inside the work of the Layout Engine





The layout pass

Pass the Layout of The - this is where Auto Layout Engine bypasses the hierarchy of concepts, but causes ViewWillLayoutSubviews method at all viewController and layoutSubviews method for all view . The layoutSubviews method updates the Frame property of each subview





When we add, change or delete constraints, they are not updated immediately. It would be inefficient to recalculate the layout and update the rendering on every change . Instead, your changes are scheduling the layout mechanism owned by window to trigger layout updates at the next opportunity in the runloop.





A typical layout cycle consists of several stages:





  1. Trigger: You are changing the input in the layout engine. This could be adding or removing subviews, changing the internal content size, activating / deactivating contstraints, or changing the priority or constant constraint.





  2. Update Model: layout engine view , views. the layout engine view.



    . Views, , setNeedsLayout() superview, layout pass runloop.





  3. Deferred Layout Pass: the layout pass view hierarchy. constraints. , , layoutSubviews() view, subviews, , views .





, viewController, view layout engine :





  • layout engine updateViewConstraints, view updateConstraints.





  • the layout pass layout engine viewWillLayoutSubviews viewDidLayoutSubviews , layoutSubviews layout





Constraints

view hierarchy , constraint' , layout engine views. updateConstraintsIfNeeded view, constraints. view, constraints, layout engine updateConstraints, . setNeedsUpdateConstraints, . , the layout engine , updateConstraintsIfNeeded.





Views

- view. the layout engine view frames .





, layout, layoutSubviews () subviews layout engine.





setNeedsLayout layoutIfNeeded, layout pass view. , layout pass view :





  • setNeedsLayout: layout. layout view layout pass application run loop.





  • layoutIfNeeded: layoutSubviews , , layout engine subviews





:

  • , constraints . the layout engine , .





  • . constraints. view layout, , the layout engine.





  • setNeedsLayout, layout'a. layoutIfNeeded view frames .












All Articles