Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a UIView zPosition?

I dont understand how to change the zPosition of a view, i try this but nothing happens :

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)] autorelease];
    view.backgroundColor = [UIColor blackColor];
    view.layer.zPosition = -400;
    [self.view addSubview:view];
}

In the CALayer doc it doesn't say anything should be done before using this property. Does anyone knows what i'm missing ?

Thanks, Vincent.

like image 874
vdaubry Avatar asked Aug 21 '10 09:08

vdaubry


1 Answers

For the zPosition of a property to have an effect in regards to the relative positioning of layers, all of the layers must be siblings of one another. That is, this won't work between different levels of a view or layer hierarchy, but will work with those at the same level of a hierarchy. You can't position a view below its superview using this, for example.

In any case, I don't think you'll see the kind of smooth animation you would like from background to foreground using the zPosition property. The instant a layer is higher in relative Z position than another sibling layer, it pops onto the screen. Even if you animate the Z position, you'll still see an instantaneous change as one layer passes another. You may need to manually animate the opacity of a layer out and then back in to achieve a smoother transition from background to foreground.

If you instead want some perspective to your layer stacking and relative positioning, see the responses to this question.

like image 82
Brad Larson Avatar answered Sep 23 '22 01:09

Brad Larson