drawRect and addSubview: custom drawing affects which views?

后端 未结 2 497
灰色年华
灰色年华 2021-02-15 14:14

If I have a custom subclass of UIView that implements drawRect and controller methods use addSubview to create a view hierarchy in this cu

相关标签:
2条回答
  • 2021-02-15 14:29

    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];
    
    0 讨论(0)
  • 2021-02-15 14:48

    -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.

    0 讨论(0)
提交回复
热议问题