2011-12-27 22 views
4

我有一個視圖,它包含在我的應用程序的主視圖中(屏幕中間的一個正方形)。我寫了下面的代碼,滑出屏幕的觀點的權利,如果你把它滑動到最左邊:如何動畫UIView離開屏幕到右側,然後再從左側重新出現

- (IBAction)swipeLeft:(id)sender 
{ 
    CGRect initCardViewFrame = self.cardView.frame; 
    CGRect movedCardToRightViewFrame = CGRectMake(initCardViewFrame.origin.x + 1000, initCardViewFrame.origin.y, initCardViewFrame.size.width, initCardViewFrame.size.height); 

    [UIView animateWithDuration:0.7 
        animations:^{self.cardView.frame = movedCardToRightViewFrame;} 
        completion:nil]; 
} 

這個偉大的工程,但是我想延長代碼,這樣一旦平方從屏幕的右側離開,它從右側回到中間。我不確定如何在窗口左側「重新繪製」它,然後將它滑回到中間。我試過重做幀,但動畫只顯示動畫塊中的最後一幀移動。我假設我需要將視圖從屏幕上移開,然後將其重新繪製在屏幕左側的外側,然後將其滑入中間。除非有更直觀的方式來做到這一點。

更新:

我下面回答了這個問題,但我不能不認爲有更好的方法來做到這一點沒有嵌套在彼此內的UIView動畫。這是解決這個問題的唯一方法嗎?

回答

4

我最終加入以下代碼「完成」參數中:

completion:^(BOOL finished) 
{ 
    self.cardView.frame = moveCardToLeftViewFrame; 

    [UIView animateWithDuration:0.4 
        animations:^{self.cardView.frame = initCardViewFrame;} 
        completion:nil]; 
}]; 

注* moveCardToLeftViewFrame是一個的CGRect是放置視圖到可視窗口的左側。所以在它向右滑動之後,它被放置在屏幕的左邊,然後滑回到中間。

+0

這是爲了得到你想要的東西的最佳方式。嵌套動畫確實變得醜陋(縮進地獄!),但這是最簡單的方法來做你想做的事情。 – jrturton 2011-12-27 18:00:07

0

可以的情況下,使用此代碼:

  1. 視圖將走出屏幕外左,獲取從右。
  2. 視圖將從屏幕熄滅到右側並從左側進入。

代碼狙擊:

- (void)animateViewWithTransformation:(MyEnumAnimationTransformation)animationTransformation withDuration:(CGFloat)duration { 
    CGFloat goOutOffScreenToX, cameInToScreenFromX; 
    switch (animationTransformation) { 
     case goOutToLeftGetInFromRight: 
      goOutOffScreenToX = -1 * [UIScreen mainScreen].applicationFrame.size.width; 
      cameInToScreenFromX = [UIScreen mainScreen].applicationFrame.size.width; 
      break; 
     case goOutToRightGetInFromLeft: 
      goOutOffScreenToX = [UIScreen mainScreen].applicationFrame.size.width; 
      cameInToScreenFromX = -1 * [UIScreen mainScreen].applicationFrame.size.width; 
      break; 
     default: 
      break; 
    } 

    CGRect originViewFrame = self.frame; 
    [UIView animateWithDuration:duration 
        animations:^{[self setX:goOutOffScreenToX];} 
        completion:^(BOOL finished) 
           { 
            [self setX:cameInToScreenFromX]; 
            [UIView animateWithDuration:duration 
                animations:^{[self setX:originViewFrame.origin.x];} 
                completion:nil]; 
           }]; 
} 
相關問題