Search code examples
swiftlayoutuikitlayoutsubviews

What actions indirectly invalidate layout, so setNeedsLayout() call is unnecessary?


I've recently started sorting out layoutSubviews(), setNeedsLayout() and layoutIfNeeded() methods. So, setNeedsLayout() manually sets the layout as invalid, so in the next update cycle (or in the current, if layoutIfNeeded() is called) views will be laid out and redrawed.

But it turned out, that if I use autolayout (i.e. constraints) and change, for example, some width constraint constant – layout automatically and indirectly invalidates and the width of the view changes with no need to call setNeedsLayout().

So, id like to know, what are other actions, that indirectly invalidate layout, so I don't need to redundantly call setNeedsLayout()?


Solution

  • There are multiple events that automatically mark a view as having changed its layout, so that layoutSubviews() will be called at the next opportunity without the developer doing this manually by calling setNeedsLayout().

    Some automatic ways to signal to the system that a view’s layout has changed are:

    • Resizing a view
    • Adding a subview
    • User scrolling a UIScrollView (layoutSubviews is called on the UIScrollView and its superview)
    • User rotating their device
    • Updating a view’s constraints

    These all communicate to the system that a view’s position needs to be recalculated and will automatically lead to an eventual layoutSubviews() call.

    Source: https://tech.gc.com/demystifying-ios-layout/