drawRect over subviews?
Asked Answered
E

3

7

I created a container view that holds a bunch of child views - a collection view, a custom toolbar and some bits and pieces.

The design has a border on the top, left and right sides, but not the bottom, so I overrode drawRect to include border.

When I added the toolbar I noticed that it appears over the top of the border. (For some reason I initially thought it wouldn't but of course it does!).

Is there anyway I can tell drawRect to draw over the top of my subviews?

Of course there's loads of other ways to solve my problem (adjust the toolbar's frame for example) however I'm asking this question in order to get a deep understanding of how drawing works in relation to compositing and the view hierarchy.

Enclasp answered 21/10, 2013 at 15:14 Comment(1)
Consider using zIndexSorcery
W
8

Drawing happens beneath all subviews of a UIView. Think of it as being on the very base - an actual part of your view - and then each subview is added on top of your view. To make the drawing above the subviews is the same as wanting for the subviews to appear under the view, while still being subviews. Perhaps that analogy makes it clearer why it must always be on the bottom. And it also leads you logically to the solution:

To get the drawing to appear above subviews, simply create a new UIView subclass to place the drawing code inside, and place this above all other subviews.

It might also be a good idea to override your UIView's addSubview: implementation, to ensure your subview always remains on top.

Woven answered 21/10, 2013 at 15:23 Comment(1)
Thanks. Crazy question in retrospect. Of course drawing must obey the view hierarchy. What else could it do?Enclasp
A
2

I believe you can't, since the drawRect is called first for the view and when it has finished drawing drawRect is called for subviews to draw over it. Maybe just make another subview on top of that view that has the borders you need and is transparent everywhere else?

Amosamount answered 21/10, 2013 at 15:23 Comment(0)
U
2

Subviews are drawn on top of their super views. So the answer to your question is no.

At the time when you draw the border on your container view, Cocoa hasn't even started drawing the toolbar yet.

I guess you could make the top of the border a subview or move the toolbar down a bit.

Ursal answered 21/10, 2013 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.