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

11,770

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

Share:
11,770
Henley
Author by

Henley

I like to work on hard technical problems.

Updated on June 04, 2022

Comments

  • Henley
    Henley about 2 years

    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];
    
  • Dan Hanly
    Dan Hanly about 13 years
    +1 On top of @Simon Lee's answer. The addSubview method should add the subview to the top without copying the object. So previously when I've had only one or two items within a view I've just called addSubview on the other item to bring it up above. This is rather unconventional however.