2013-04-04 2 views
4

Я хочу выполнить флип-анимацию, когда пользователь перетаскивает палец с правой стороны экрана. Состояние анимации должно зависеть от длины перетаскивания и не должно работать автоматически.Как выполнить флип-анимацию между двумя видами, перетаскивая палец?

я использовал что-то вроде этого:

if (transitionBegan) { 

    flipTransition = CATransform3DIdentity; 
    flipTransition.m34 = 1.0/-500; 
    flipTransition = CATransform3DRotate(flipTransition, degree * M_PI/180.0f,0.0f, 1.0f, 0.0f); 
    self.view.layer.transform = flipTransition; 
} 

Но теперь я не знаю, как реализовать переход между моими взглядами, так что мнение исчезает и появляется вид B.

Вы можете мне помочь?

+0

Я предполагаю, что вы говорите о флип который прогрессирует (или останавливается), когда палец пользователя перемещается (или приостанавливается). Я думаю, вам нужно использовать пользовательский контейнер в этой ситуации, используя «UIPanGestureRecognizer». [This post] (http://stackoverflow.com/questions/15703613/navigating-uiviewcontrollers-with-gestures-in-ios/15747892#15747892) показывает, как сделать это с помощью анимации push-стиля, но можно настроить на сделайте флип-аннотацию тоже. – Rob

ответ

0

Используйте метод UIView animateWithDuration: animations: completion:, чтобы анимировать текущий вид до точки перехода, затем в блоке завершения удалите текущее представление, добавьте новое представление и запустите новую аналогичную анимацию на новом представлении.

2

Вы должны быть в состоянии сделать это с помощью UIPanGestureRecognizer (распознаватель жестов, который прослушивает перетаскивание пальцев), вы сможете получить длину панорамы, а оттуда рассчитать CATransform3D переводов и масштабирования после выполнения панорамирования.

(Встроенные анимации не полезны там, вы должны сделать некоторые использование CoreAnimation здесь, это интересно, я могу вам сказать ;-))

3

Вы можете написать жест распознаватель, который делает transform для вы. Например, предположив, что вы можете перевернуть как влево, так и вправо, вы можете сделать что-то вроде следующего. Но идея состоит в том, что вы преобразовать текущий вид, если вы меньше, чем половина пути через флип, и если преобразовать следующий вид более чем на полпути через него:

- (void)handlePan:(UIPanGestureRecognizer *)gesture 
{ 
    static UIView *currentView; 
    static UIView *previousView; 
    static UIView *nextView; 

    if (gesture.state == UIGestureRecognizerStateBegan) 
    { 
     // Set the three view variables here, based upon the logic of your app. 
     // If there is no `previousView` or `nextView`, then set them to `nil` 
     // as appropriate. 

     // I happen to be choosing views for child view controllers for my 
     // custom container, but I'll spare you that in case you're not using 
     // custom container controller. 
    } 

    // lets set the "percent" rotated as the percent across the screen the user's 
    // finger has travelled 

    CGPoint translation = [gesture translationInView:gesture.view.superview]; 
    CGFloat percent = translation.x/gesture.view.frame.size.width; 
    CGFloat rotationPercent = percent; 

    // let's use the var to keep track of which view will be rotated 

    UIView *viewToTransform = nil; 

    if (percent < -0.5 && nextView) 
    { 
     // if user has moved finger more than half way across the screen to 
     // the left, and there is a `nextView`, then we're showing the second 
     // half of flip to the next screen 

     currentView.hidden = YES; 
     nextView.hidden = NO; 
     previousView.hidden = YES; 
     rotationPercent += 1.0; 
     viewToTransform = nextView; 
    } 
    else if (percent > 0.5 && previousView) 
    { 
     // if user has moved finger more than half way across the screen to 
     // the right, and there is a `previousView`, then we're showing the second 
     // half of flip to the previous screen 

     currentView.hidden = YES; 
     nextView.hidden = YES; 
     previousView.hidden = NO; 
     rotationPercent -= 1.0; 
     viewToTransform = previousView; 
    } 
    else if ((percent < 0 && nextView) || (percent > 0 && previousView)) 
    { 
     // otherwise we're in the first half of the flip animation, so we're 
     // showing the `currentView` 

     currentView.hidden = NO; 
     nextView.hidden = YES; 
     previousView.hidden = YES; 
     viewToTransform = currentView; 
    } 

    // do the flip `transform` 

    CATransform3D transform = CATransform3DIdentity; 
    transform.m34 = 1.0/-800; 
    viewToTransform.layer.transform = CATransform3DRotate(transform, M_PI * rotationPercent, 0.0, 1.0, 0.0); 

    // if we're all done, let's animate the completion (or if we didn't move far enough, 
    // the reversal) of the pan gesture 

    if (gesture.state == UIGestureRecognizerStateEnded || 
     gesture.state == UIGestureRecognizerStateCancelled || 
     gesture.state == UIGestureRecognizerStateFailed) 
    { 
     // I'm personally using an index of my custom container child views, so I'm 
     // just updating my index appropriately; your logic may obviously differ 
     // here. 

     if (percent < -0.5 && nextView) 
      self.currentChildIndex++; 
     else if (percent > 0.5 && previousView) 
      self.currentChildIndex--; 

     // and animate the completion of the flip animation 

     [UIView animateWithDuration:0.25 
           delay:0.0 
          options:UIViewAnimationOptionCurveEaseInOut 
         animations:^{ 
          previousView.transform = CGAffineTransformIdentity; 
          currentView.transform = CGAffineTransformIdentity; 
          nextView.transform = CGAffineTransformIdentity; 
         } 
         completion:NULL]; 
    } 
} 
+0

С iOS 7 вы можете использовать интерактивные пользовательские переходы (см. Http://stackoverflow.com/a/10407713/1271826), используя анимацию UIView на основе блоков. Я соответствующим образом обновлю ответ. – Rob

Смежные вопросы