0

我正在尝试动画从窗口滑出一个视图并同时滑入另一个视图。像这样:

     Window
------------------  
|----------------| ------------------
||              || |                |
||     view     || |      view      |
||  sliding out || |   sliding in   |
|----------------| ------------------
------------------  
      <---                <---

我正在使用图层支持的视图,尝试使用隐式动画和 CATransaction。发生的事情是视图滑出动画,但滑入的视图只是跳到位。这是我的代码:

    NSView *slidingInView = nil;
    NSView *slidingOutView = nil;
    if (currentState.primaryView != nextState.primaryView) {
        // Slide in a primary view
        [self.window.contentView addSubview:nextState.primaryView];
        CGRect frame = nextState.primaryView.layer.frame; 
        frame.origin.x = slideFromRight ? frame.size.width : 0 - frame.size.width;
        [nextState.primaryView.layer setPosition: frame.origin];

        slidingInView = nextState.primaryView;
        slidingOutView = currentState.primaryView;
    }

    [CATransaction begin];
    [CATransaction setValue:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]
                     forKey:kCATransactionAnimationTimingFunction];
    [CATransaction setAnimationDuration:1.0f];
    [CATransaction setCompletionBlock:^{
        [slidingOutView removeFromSuperview];
    }];

    // Slide in the new view
    slidingInView.layer.position = CGPointMake(0.0f, 0.0f);

    // if there is a view in place already, slide it out to the left.
    if (slidingOutView != nil) {

        CGRect frame = slidingOutView.layer.frame;
        frame.origin = CGPointMake(slidingOutView.layer.frame.size.width, slidingOutView.layer.frame.origin.y);
        if (slideRight)
            frame.origin = CGPointMake(0-slidingOutView.layer.frame.size.width, slidingOutView.layer.frame.origin.y);

        [slidingOutView.layer setPosition: frame.origin];
    }

    [CATransaction commit];

这对我来说完全是个谜。有人有线索吗?我的窗口的 contentView 有 setWantsLayer: YES,就像我滑入的所有视图一样。

4

1 回答 1

2

隐式动画仅适用于独立层(不支持视图的层)。

您需要显式地为图层设置动画(并更改属性值,因为默认情况下不会发生)。它看起来像

CABasicAnimation *slideIn = [CABasicAnimation animationWithKeyPath:@"position"];
[slideIn setToValue:[NSValue valueWithCGPoint:myNewEndPoint]];
[slideIn setFromValue:[NSValue valueWithCGPoint:[[slidingInView layer] position]]];
[[slidingInView layer] addAnimation:slideIn forKey:@"mySlideInAnimation"];
[[slidingInView layer] setPosition:myNewEndPoint];

另外:除非您更改了锚点,否则图层的位置应该在中心(这意味着将其设置为(0,0)将使图层的 3/4 出现在屏幕外

于 2012-06-22T20:27:51.627 回答