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.

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.


You can easily animate zPosition property of CALayer using UIView.transitionWithView().

var isFirstViewOnTop = true
func switchCards() {
    self.isFirstViewOnTop = !self.isFirstViewOnTop

    UIView.transitionWithView(
        self,
        duration: 0.25,
        options: .TransitionCrossDissolve,
        animations: { () -> Void in
            self.firstView.layer.zPosition = self.isFirstViewOnTop ? 1 : 0
            self.secondView.layer.zPosition = !self.isFirstViewOnTop ? 1 : 0
        },
        completion: nil
    )
}

Need Your Help

Creating a regasm'ed object in javascript

javascript dll com activex regasm

For reasons I won't get in to, I have to create an object from a .NET dll in javascript. The browser I'm using is some ridiculous proprietary thing, but that means it has no security settings, so ...

Fastest way to apply alpha channel to image in OpenCV

c++ opencv optimization

I'm currently using the following function to apply my alpha channels (stored as separate GRAY cv::Mats), to images: