Difference between setNeedsLayout() & layoutIfNeeded()

Manish Pathak
2 min readDec 2, 2020

--

setNeedsLayout()

  • It gives the signal to the ui engine to update the view when next ui updation cycle occurs.
  • setNeedsLayout() does not force an immediate update, but instead waits for the next update cycle.
  • It always calls on the main thread.
  • If you are not using any animation, setNeedslayout() is sufficient to trigger layoutSubViews() to update the view. layoutIfNeeded() is not needed in almost all cases.

layoutIfNeeded()

  • layoutIfNeeded() is needed to force the view to update its layout immediately but it always needs the signal otherwise it’ll not update the layout.
  • layoutIfNeeded() cannot trigger layoutSubViews() on its own. It needs a signal, it always needs a signal before layoutIfNeeded() can have effect on the view.
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
  • above code will not trigger the layoutSubViews() , hence no update will happen. so what needs to be done to animate the views.
view.setNeedsLayout()
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
  • In the above code, we first call setNeedsLayout() to set a signal to the system that we want to update the view. Then the signal will allow the layoutIfNeeded() function to take effect. And, due to the nature of layoutIfNeeded() function, which is to force the view to update immediately, an animation is possible.

setNeedsLayout() has no animation capability but layoutIfNeeded() has. Thus, layoutIfNeeded() should always appear in the animation block to trigger the animation. Else, calling setNeedsLayout() without an animation block is enough to update the view when the animation is not needed.

Question: Does this mean that we should always call setNeedsLayout() before calling layoutIfNeeded()?

No , its not mandatory. for safety purposes you can always call setNeedsLayout() before calling the layoutIfNeeded(). it’s redundant and shows the lack of knowledge about how UI cycle works .

--

--