Abhinav
Abhinav

Reputation: 38162

Importance of drawRect, layoutSubViews and setNeedsDisplay methods

What is the importance of drawRect, layoutSubViews and setNeedsDisplay methods. In which contexts we should use them?

Upvotes: 3

Views: 2902

Answers (1)

vodkhang
vodkhang

Reputation: 18741

As in the documentation says:

drawRect: Draws the receiver’s image within the passed-in rectangle. 

Parameters

rect : A rectangle defining the area to restrict drawing to.

You use this method to draw your UIView inside a specific rect of a view.

  • (void)setNeedsDisplay

By default, geometry changes to a view automatically redisplays the view without needing to invoke the drawRect: method. Therefore, you need to request that a view redraw only when the data or state used for drawing a view changes. In this case, send the view the setNeedsDisplay message. Any UIView objects marked as needing display are automatically redisplayed when the application returns to the run loop.

I think that this method let you control if you want the system automatically redraw your UIView for you or not. If you want to control the process by your own state like: if the user click this button, redraw; otherwise, don't.

Lays out subviews.

  • (void)layoutSubviews

Overridden by subclasses to layout subviews when layoutIfNeeded is invoked. The default implementation of this method does nothing.

I have not much experience with this method. What I can tell you is that you need to override it to layout your subviews

Upvotes: 2

Related Questions