2012-06-22 132 views
0

我想動畫從一個窗口滑出一個視圖並同時在另一個視圖中滑動。像這樣:隱式CALayer動畫不生成動畫

 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,因爲我滑動的所有視圖都如此。

回答

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層出現在屏幕外

+0

非常好!這正是醫生的要求,我非常喜歡隱式動畫的簡單性,但是這個效果很好;)順便說一句,valueWithCGPoint沒有在Mac上定義,所以我'm使用valueWithPoint接受NSPoint,所以我需要投射,這很醜陋。無論如何,謝謝! –

+0

啊,我很習慣iOS,我忘記了它與NSValue的區別 –