Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawRect and addSubview: custom drawing affects which views?

If I have a custom subclass of UIView that implements drawRect and controller methods use addSubview to create a view hierarchy in this custom view, how does drawRect interact with these subviews? Does it recreate the entire subclass's view hierarchy from scratch and remove any existing subviews? Or does it ignore subviews and only redraw a particular view/subview?

Would it be acceptable to programmatically add and remove subviews within drawRect?

like image 221
johnbakers Avatar asked Aug 29 '11 03:08

johnbakers


2 Answers

drawRect is meant to be only for drawing your content in the view.

Whether it draws the entire view or part of it: It depends on your implementation. If you want to do any optimization is a good idea to check when your view calls drawRect and adjust the code accordingly (maybe you want to update only one part of the view, maybe you don't want to draw all the times, etc). It depends on your needs

I don't think is a good idea to add/remove subviews within drawRect because this method will be called in several situations and I dare to say that is NOT what you want :)

Instead, you could try something like this:

[myView addSubview:aSubview];
[myView setNeedsDisplay];
//or calculate the needed display rect by yourself and then
[myView setNeedsDisplayInRect:aRect];
like image 136
nacho4d Avatar answered Nov 14 '22 09:11

nacho4d


-drawRect: doesn't interact with subviews. It draws whatever the view it's sent to wants to draw in the rect it's given.

Would it be acceptable to programmatically add and remove subviews within drawRect?

NO. -drawRect: is for drawing, not for manipulating the view hierarchy.

like image 5
NSResponder Avatar answered Nov 14 '22 08:11

NSResponder