Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView Positioning for iPhone: Any concept of "Z-Index"?

I know if I want to add a black background to a UIImageView, I can create an UIImageView that is a bit smaller than the UIView it's contained in. If I do this, the UIImageView is positioned on top of the black background.

Just hypothetically speaking, suppose I want the black background UIView on TOP of the UIImageView (so that it covers the image), how do I do this? Is there a concept of a z-index?

Here's my code to add a black background to an image:

UIView *blackBG = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];

blackBG.backgroundColor = [UIColor blackColor];

UIImageView *myPicture = [[UIImageView alloc] initWithImage:
                          [UIImage imageNamed: @"myPicture.jpg"]];

int borderWidth = 10;

myPicture.frame = CGRectMake(borderWidth,
                             borderWidth,
                             blackBG.frame.size.width-borderWidth*2,
                             blackBG.frame.size.height-borderWidth*2)];

[blackBG addSubview: myPicture];
like image 389
Henley Avatar asked Nov 28 '22 14:11

Henley


1 Answers

Subviews are layered, you can send a subview to the back with...

[myView sendSubviewToBack:mySubView];

or bringSubviewToFront etc.

You can also do one of these...

[myView insertSubview:mySubview atIndex:0]; //Places it at the bottom

[myView insertSubview:mySubview belowSubview:anotherSubview]; //Places it below anotherSubview

As soon as you add a view as a subview to another view however, the parent view is the bottom of the stack. You can play around with CALayer z orders but you are bypassing the general approach of views and subviews.

Create a single view as a parent for both the bg view and the imageview, then you can order them how you like.

UPDATE: I have a UIView+Layout category which has nice [subview sendToBack]; and [subview bringToFront]; which you may find useful.... article here

like image 170
Simon Lee Avatar answered Dec 19 '22 00:12

Simon Lee