Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need to call setNeedsDisplay in iOS?

When creating an iOS app, I'm confused as to when exactly I need to call setNeedsDisplay? I know that it has something to do with updating/redrawing the UI; however, do I need to call this every time I change any of my views?

For example, do I need to call it:

  • After programatically changing the text in a text field
  • When changing the background of a view?
  • When I make changes in viewDidLoad?
  • How about in viewDidAppear?

Could someone give me some general guidelines regarding when to use this method?

like image 809
Nosrettap Avatar asked May 30 '12 14:05

Nosrettap


People also ask

What does setNeedsDisplay do?

setNeedsDisplay()Marks the receiver's entire bounds rectangle as needing to be redrawn.

What is a view in Swift?

Views are the fundamental building blocks of your app's user interface, and the UIView class defines the behaviors that are common to all views. A view object renders content within its bounds rectangle, and handles any interactions with that content.


1 Answers

You should only be calling setNeedsDisplay if you override drawRect in a subclass of UIView which is basically a custom view drawing something on the screen, like lines, images, or shapes like a rectangle.

So you should call setNeedsDisplay when you make changes to few variables on which this drawing depends and for view to represent that change , you need to call this method which internally will give a call to drawRect and redraw the components.

When you add an imageView or a UIButton as a subview or make changes to any subview, you need not call this method.

Example:

You have a view that shows a moving circle, either you touch and move it, or may be timer based animation. Now for this, you will need a custom view that draws a circle at given center and with given radius. These are kept as instance variables which are modified to move the circle by changing its center or make it bigger by increasing radius of it.

Now in this case either you will modify these variables(centre or radius) in a loop and timer Or may be by your fingers in touchesEnded and touchesMoved methods. To reflect the change in this property you need to redraw this view for which you will call setNeedsDisplay.

like image 155
Amogh Talpallikar Avatar answered Oct 19 '22 05:10

Amogh Talpallikar