0

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()?

2 Answers2

0

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/

0

You need call setNeedsLayout of some view, if you have subclassed some View and override layoutSubviews method. And in that implementation you have some conditions, that affects method behaviour. So you need call setNeedsLayout every time when condition change. If you use autolayout obviously you haven't override layoutSubviews and don't need call setNeedsLayout

Cy-4AH
  • 4,370
  • 2
  • 15
  • 22