setNeedsLayout and setNeedsDisplay
Asked Answered
N

1

72

What is the real difference between UIView methods setNeedsLayout and setNeedsDisplay?

As usual documentation is foggy about this.

Nightrider answered 24/1, 2013 at 17:15 Comment(0)
L
104

Actually the documentation is pretty clear about this:

  • setNeedsLayout will layout subviews

    Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews.

  • setNeedsDisplay will call for a redraw of your view (drawRect:, etc).

    You can use this method or the setNeedsDisplayInRect: to notify the system that your view’s contents need to be redrawn.

Ladylove answered 24/1, 2013 at 17:18 Comment(6)
no, I was wondering more in terms of both are used to redraw the view, right? Both will wait until the next draw cycle to be redrawn, right?Nightrider
Layout is not about drawing. Layout is about positioning/sizing subviews. But yes, both delay to the next runloop cycle. So calling one multiple times in a row will only result in one relayout/redraw.Ladylove
Please provide an example of when setNeedsDisplay is needed.Meshuga
Call setNeedsDisplay to make sure your view redraws itself. A common use case is to call this after changing a property of your class that's used during drawing.Ladylove
@Meshuga Say you want to draw a line between two dots (two UIView, exactly), this is implemented in drawRect: of DrawLineView. After you change the position of one button or both of them, you need to call [drawLineView setNeedsDisplay]; to redraw the line between new position of the two dots.Ordinal
@Meshuga blog.fujianjin6471.com/2015/06/11/…Ordinal

© 2022 - 2024 — McMap. All rights reserved.