2009-09-21 75 views
5

我正在爲正在製作的紙牌遊戲添加一些基本動畫。 (我的第一個iPhone應用程序)開始動畫之前修改iPhone動畫容器視圖

我正在創建一個自定義的UIView類「AnimationContainer」,它從image1翻轉到image2,同時從rect1移動到rect2。我的最終目的是讓這些容器中的四個同時進行轉換。

我遇到的問題是動畫不顯示image1 ...所以只有翻轉過渡的後半部分出現。

但是,如果我首先通過觸摸重置來重置動畫,那麼一切正常。換句話說,如果我一次又一次地按Flip,我只能得到一半的過渡...但是如果我先按Reset,那麼一次翻轉就完美了。

那麼,我怎樣才能讓動畫正確地重置?

以下是代碼和屏幕截圖,下面是完整鏈接:Project Zip File 700k

alt text http://www.robsteward.com/cardflip.jpg

- (void)displayWithImage1 {  //RESET button calls this 
    self.frame = rect1; 
    [image2 removeFromSuperview]; 
    [self addSubview:image1]; 
    [self setNeedsDisplay]; //no help: doesn't force an update before animation 
} 

- (void)runTheAnimation {  //FLIP button calls this 
    [self displayWithImage1]; //<---this is what the reset button calls 
    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.5]; 
    [UIView setAnimationTransition:transition forView:self cache:NO]; 
    self.frame = rect2; 
    [image1 removeFromSuperview]; 
    [self addSubview:image2]; 
    [UIView commitAnimations]; 
} 

謝謝!

+0

我想出了一個半醜的解決方法。我添加了一個「虛擬」動畫,並讓我的班級成爲其setAnimationDidStopSelector的代表。虛擬動畫的持續時間爲0.0,並將視圖移動到rect1。當虛擬的停止選擇器被調用時,我從上面執行「真實」的動畫翻轉代碼。功能齊全,看起來至少有4個可以同時運行。耶,我。 LOL – Rob 2009-09-21 21:16:34

+1

原來,解決方法可能會產生長達半秒的延遲,所以我開始賞金。必須有一種方法來發送一個容器視圖兩個圖像,並在一次轉換中將其從一個翻轉到另一個。 – Rob 2009-10-01 02:22:24

回答

12

爲了在執行動畫之前重新繪製視圖,需要傳遞一個繪製循環。這段代碼就是「繪製這個的一個例子,當下一個事件循環出現時,做其他事情。」在UI代碼中執行此操作並不罕見。你的第一個解決方法是嘗試同樣的事情,但以更復雜的方式。

- (void)_runTheAnimation { 
    // Moved here from -runTheAnimation 
    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.5]; 
    [UIView setAnimationTransition:transition forView:self cache:NO]; 
    self.frame = rect2; 
    [image1 removeFromSuperview]; 
    [self addSubview:image2]; 
    [UIView commitAnimations]; 
} 

- (void)runTheAnimation {  //FLIP button calls this 
    [self displayWithImage1]; 
    [self performSelector:@selector(_runTheAnimation) withObject:nil afterDelay:0.0]; 
} 
+1

太棒了!非常感謝。我完全不清楚選擇器是否立即執行。現在一切都很好。 200代表賞金是一個小的代價。我花了10個小時搞這個。 – Rob 2009-10-01 03:21:26

+1

如果要求(-peformSelector :)立即發送選擇器,則上面的方法是-performSelector:withObject:afterDelay:,它將在選擇器的runloop上進行調度,以便將來在某個點發送。延遲0有效意味着「下一次運行循環迭代」。選擇器本身只是描述了傳遞給對象的消息。傳遞該消息的行爲由performSelector ...方法完成。 – 2009-10-01 11:50:53

+1

很酷,我想我明白了。仍然在加速Cocoa,Objective-C和iPhone的所有事情......但我現在學得更快。再次感謝。 – Rob 2009-10-01 15:26:18