2010-11-07 108 views
4

我移植了iPhone應用程序的Mac OS X.此代碼是被成功地使用在iPhone上:爲什麼我的CATransaction不遵守我設定的時間?

- (void) moveTiles:(NSArray*)tilesToMove { 
    [UIView beginAnimations:@"tileMovement" context:nil]; 
    [UIView setAnimationDuration:0.1]; 
    [UIView setAnimationDelegate:self]; 
    [UIView setAnimationDidStopSelector:@selector(tilesStoppedMoving:finished:context:)]; 

    for(NSNumber* aNumber in tilesToMove) { 
     int tileNumber = [aNumber intValue]; 
     UIView* aView = [self viewWithTag:tileNumber]; 
     aView.frame = [self makeRectForTile:tileNumber]; 
    } 

    [UIView commitAnimations]; 
} 

Mac版本使用CATransaction到組動畫,就像這樣:

- (void) moveTiles:(NSArray*)tilesToMove { 
    [CATransaction begin]; 
    [CATransaction setAnimationDuration:0.1]; 
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; 
    [CATransaction setCompletionBlock:^{ 
     [gameDelegate tilesMoved]; 
    }]; 

    for(NSNumber* aNumber in tilesToMove) { 
     int tileNumber = [aNumber intValue]; 
     NSView* aView = [self viewWithTag:tileNumber]; 
     [[aView animator] setFrame:[self makeRectForTile:tileNumber]]; 
    } 

    [CATransaction commit]; 
} 

動畫執行正常,但持續時間爲1.0秒。我可以改變setAnimationDuration:調用任何東西,或完全忽略它,並且動畫的持續時間爲每秒1.0秒。我也不認爲setAnimationTimingFunction:call是做什麼的。但是,setCompletionBlock:正在工作,因爲該塊在動畫完成時正在執行。

我在這裏做錯了什麼?

回答

5

如果我沒有弄錯你不能使用CoreAnimation直接爲NSView的動畫。爲此你需要NSAnimationContext和[NSView animator]。 CATransaction僅適用於CALayers。

+0

啊。我找不到任何明確說明的文件,但是,那肯定會解釋它。 – zpasternack 2010-11-10 04:33:38

2

它沒有完全回答問題,但我最終使用NSAnimationContext而不是CATransaction。

- (void) moveTiles:(NSArray*)tilesToMove { 
    [NSAnimationContext beginGrouping]; 
    [[NSAnimationContext currentContext] setDuration:0.1f]; 

    for(NSNumber* aNumber in tilesToMove) { 
     int tileNumber = [aNumber intValue]; 
     NSView* aView = [self viewWithTag:tileNumber]; 
     [[aView animator] setFrame:[self makeRectForTile:tileNumber]]; 

     CAAnimation *animation = [aView animationForKey:@"frameOrigin"]; 
     animation.delegate = self; 
    } 

    [NSAnimationContext endGrouping]; 
} 

這是有效的,但我對此並不滿意。主要的是,NSAnimationContext沒有像CATransaction那樣的回調完成機制,所以我不得不把這個東西放在那裏來顯式地獲取視圖的動畫並設置委託,這樣就可以觸發回調。問題在於,每次動畫都會觸發多次。事實證明,對於我正在做的事情沒有不良影響,它只是感覺不對。

這是可行的,但如果有人知道更好的解決方案,我仍然喜歡一個。

相關問題