2

What are the differences between adding a view as a subView VS drawing the view in that view's drawRect method?.

I use both approaches, but I was wondering apart from the obvious such as, if you do in drawRect it will be a single View, as opposed as two views, or adding as a subview is just easier. Are there any specific situations where you should definitely use one over the other?

Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118

2 Answers2

4

Overriding -drawRect: can be a good way to draw complex UITableViewCells. Having all of the subviews composited and drawn as one view helps table view scrolling performance immeasurably.

Having said that, I typically stick with the highest level API available and drop down to a lower level only if performance suffers.

Mark Adams
  • 30,776
  • 11
  • 77
  • 77
  • Thanks for this. In my app, cells can have lots of subviews (no limit, but usually between 5 and 20), and I've been reported that with the 3GS it's not really smooth. Now I have an idea why! – ksol Jan 12 '12 at 21:41
  • It's a huge problem if those subviews have any alpha at all. The GPU is definitely working hard trying to do all that compositing for every frame in 1/60th of a second. If the drawing doesn't finish in time, that frame is dropped resulting in a choppy performance. – Mark Adams Jan 12 '12 at 21:42
  • the subviews are custom labels with a gradient background, I don't tweak with opacity. But still, might come from that – ksol Jan 12 '12 at 21:45
4

Adding a subview is easier as you point out, and I really see this as no contest in 90% of cases. You should generally add a subview and let the libraries handle drawing of subviews in their correct position.

I only use -drawRect: to accomplish custom drawing within my view, but not to draw subviews, it creates unnecessary complexity. If you need a lot of performance, -drawRect: can help you there. Also, in the case of simple drawing, -drawRect: is very nice as opposed to making several subviews. But in general, it pays to just add a subview.

If in the future you decide you want these subviews to receive touch events or handle things interactively, it is more difficult to refactor your -drawRect: code.

Kekoa
  • 27,892
  • 14
  • 72
  • 91