0

我在應用程序中以模態方式呈現視圖控制器。我希望用戶能夠用手勢「彈開」視圖。我寫了下面的代碼:動畫無法正常工作

- (void)handlePan:(UIPanGestureRecognizer *)recognizer { 
    CGFloat elasticThreshold = 100; 
    CGFloat dismissThreshold = 200; 
    CGPoint translation = [recognizer translationInView:self.view]; 
    CGFloat newY = 0; 
    CGFloat translationFactor = 0.5; 

    if (recognizer.state == UIGestureRecognizerStateEnded) { 
     if (translation.y < dismissThreshold) { 
      newY = 0; 
     } 
    } else { 
     if (translation.y > elasticThreshold) { 
      CGFloat frictionLength = translation.y - elasticThreshold; 
      CGFloat frictionTranslation = 30 * atan(frictionLength/120) + frictionLength/10; 
      newY = frictionTranslation + (elasticThreshold * translationFactor); 
     } else { 
      newY = translation.y*translationFactor; 
     } 
    } 

    if (translation.y > dismissThreshold) { 
     [UIView animateKeyframesWithDuration:0.5 delay:0.0 options:0 animations:^{ 
      [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{ 
       self.overlay.effect = nil; 
       self.collectionView.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height); 
      }]; 
      [UIView addKeyframeWithRelativeStartTime:0.1 relativeDuration:0.1 animations:^{ 
       self.pageControl.frame = CGRectMake((self.view.frame.size.width-200)/2, self.view.frame.size.height, 200, 20); 
      }]; 
     } completion:^(BOOL finished) { 
      if (finished) { 
       [self dismissViewControllerAnimated:YES completion:nil]; 
      } 
     }]; 
    } else { 
     self.collectionView.transform = CGAffineTransformMakeTranslation(0, newY); 
     self.pageControl.transform = CGAffineTransformMakeTranslation(0, (newY+self.collectionView.frame.size.height)-20); 
    } 
} 

這是迷上了一個UIGestureRecognizer

self.pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; 
self.pan.delegate = self; 
self.pan.maximumNumberOfTouches = 1; 
[self.view addGestureRecognizer:self.pan]; 

但是,什麼情況是,在完成塊立即執行。所以你會看到視圖向下移動(因爲dismissViewControllerAnimated),並且同時看到overlay.effect消失。然而,我想要的是讓我的動畫發生,然後視圖控制器默默地解散它自己。

任何想法這裏有什麼問題嗎?

+0

手勢處理的其他部分發生了什麼?手勢狀態改變時您是否在移動視圖?在平底鍋結束時只做任何事情似乎很奇怪 – jrturton

+0

當平底鍋結束時我將它移回到0。否則我會把視線向下移動,是的。 – user4992124

+0

但該代碼不在您的問題 – jrturton

回答

0

發生這種情況是因爲您是嵌套UIView動畫塊。您應該使用dispatch_after此:

double delayInSeconds = 0.5; 
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
    [self dismissViewControllerAnimated:YES completion:nil]; 
}); 
+0

我不是嵌套?我只是將關鍵幀添加到'animateKeyframesWithDuration'。但推遲視圖控制器的解僱可能會奏效,是的。 – user4992124

+0

@ user4992124問題是您正在主塊內部調用塊,並且會觸發完成塊比預期更早運行。 – the4kman

+0

這仍然導致視圖幾乎立即被解僱。 – user4992124

0

一個UIView關鍵幀(或標準)的動畫將立即執行其完成塊,如果沒有工作要做。如果沒有任何動畫,它將不會等待動畫的持續時間。

在你的情況下,當你開始關閉解除動畫時,視圖已經處於最終狀態,因此沒有動畫,並且完成塊立即運行。