How to change a UIView zPosition?

2019-05-17 05:55发布

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.

2条回答
冷血范
2楼-- · 2019-05-17 06:39

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.

查看更多
何必那么认真
3楼-- · 2019-05-17 06:39

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
    )
}
查看更多
登录 后发表回答