Подтвердить что ты не робот

Вертикальная флип-анимация UIView

У меня есть iOS UIView с UIViewAnimationTransitionFlipFromRight. Мне нужно, чтобы он переворачивался вертикально. Переход к лоскуту страницы не приведет к его сокращению. Я предполагаю, что для этого потребуется что-то обычное.

Любые идеи?

4b9b3361

Ответ 1

Как и в iOS 5.0, нет необходимости писать собственное преобразование Core Animation для выполнения вертикальных переворотов. Просто используйте переходы UIKit UIViewAnimationOptionTransitionFlipFromTop и UIViewAnimationOptionTransitionFlipFromBottom, и все это становится единственным вызовом метода.

Они ведут себя аналогично UIViewAnimationOptionTransitionFlipFromLeft и UIViewAnimationOptionTransitionFlipFromRight (которые были вокруг с iOS 2.0).

Пример использования:

[UIView transitionFromView:viewToReplace
                    toView:replacementView
                  duration:1
                   options:UIViewAnimationOptionTransitionFlipFromBottom
                completion:nil];

Вышеприведенный код будет вертикально переворачивать надпись viewToReplace. На полпути в анимации, в тот момент, когда супервизор перпендикулярен экрану и, таким образом, невидим, viewToReplace заменяется на replacementView.

Это легко.

Ответ 2

Просто напишите свой собственный метод для флип, используя Core Animation Transforms.

- (void)verticalFlip{
    [UIView animateWithDuration:someDuration delay:someDelay animations:^{
        yourView.layer.transform = CATransform3DMakeRotation(M_PI,1.0,0.0,0.0);
    } completion:^{
        // code to be executed when flip is completed
    }];
}

Убедитесь, что вы добавили и включили библиотеки и фреймворки Core Animation, а также включили math.h, если хотите использовать нотацию M_PI.

EDIT:

Чтобы по существу "изменить" представление, когда он перевернулся, сделайте примерно следующее:

- (void)verticalFlip{
    [UIView animateWithDuration:someDuration delay:someDelay animations:^{
        yourView.layer.transform = CATransform3DMakeRotation(M_PI_2,1.0,0.0,0.0); //flip halfway
    } completion:^{
        while ([yourView.subviews count] > 0)
            [[yourView.subviews lastObject] removeFromSuperview]; // remove all subviews
        // Add your new views here 
        [UIView animateWithDuration:someDuration delay:someDelay animations:^{
            yourView.layer.transform = CATransform3DMakeRotation(M_PI,1.0,0.0,0.0); //finish the flip
        } completion:^{
            // Flip completion code here
        }];
    }];
}

Это также может работать:

- (void)verticalFlip{

    // Do the first half of the flip
    [UIView animateWithDuration:someDuration delay:someDelay animations:^{
        yourView.layer.transform = CATransform3DMakeRotation(M_PI_2,1.0,0.0,0.0); //flip halfway
    } completion:^{
        while ([yourView.subviews count] > 0)
            [[yourView.subviews lastObject] removeFromSuperview]; // remove all subviews
        // Add your new views here 
    }];

    // After a delay equal to the duration+delay of the first half of the flip, complete the flip
    [UIView animateWithDuration:someDuration delay:durationOfFirstAnimation animations:^{
        yourView.layer.transform = CATransform3DMakeRotation(M_PI,1.0,0.0,0.0); //finish the flip
    } completion:^{
        // Flip completion code here
    }];
}

Приветствия.

Ответ 3

Код от Brenton не работал для меня, поэтому я немного покопался в документах Apple и нашел этот фрагмент кода для горизонтального отражения:

- (IBAction)toggleMainViews:(id)sender {
    [UIView transitionFromView:(displayingPrimary ? primaryView : secondaryView)
                        toView:(displayingPrimary ? secondaryView : primaryView)
                      duration:1.0
                       options:(displayingPrimary ? 
                                    UIViewAnimationOptionTransitionFlipFromRight :
                                    UIViewAnimationOptionTransitionFlipFromLeft)
                    completion:^(BOOL finished) {
                                   if (finished) {
                                       displayingPrimary = !displayingPrimary;
                                   }
                              }
    ];
}

Вы можете сделать вертикальный переворот, изменив параметры с UIViewAnimationOptionTransitionFlipFromRight : UIViewAnimationOptionTransitionFlipFromLeft на UIViewAnimationOptionTransitionFlipFromTop : UIViewAnimationOptionTransitionFlipFromBottom.

Работал как шарм.

Ответ 4

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

Просто создайте преобразование, используя CATransform3DMakeRotation, недостаточно, нет светового эффекта, нет перспективы. Я пишу образец, чтобы добавить этот эффект. Вы можете легко изменить его на интерактивный переход.

Демо:

Flip effect

Пример кода:

CALayer *sideALayer = sideAView.layer;
CALayer *sideBLayer = sideBView.layer;
CALayer *containerLayer = containerView.layer;

sideALayer.opacity = 1;
sideBLayer.opacity = 0;
sideBLayer.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
containerLayer.transform = CATransform3DIdentity;

CATransform3D perspectiveTransform = CATransform3DIdentity;
perspectiveTransform.m34 = -1.0 / containerViewWidth;
[UIView animateKeyframesWithDuration:1 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{

    [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.5 animations:^{
        sideALayer.opacity = 0;
        containerLayer.transform = CATransform3DConcat(perspectiveTransform,CATransform3DMakeRotation(M_PI_2, 0, 1, 0));
    }];
    [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
        sideBLayer.opacity = 1;
        containerLayer.transform = CATransform3DConcat(perspectiveTransform, CATransform3DMakeRotation(M_PI, 0, 1, 0));
    }];
} completion:nil];

sideAView и sideBView являются областями viewView контейнера.

В контейнере установлен черный фон.

Ответ 5

версия Swift 4.0 100% рабочее решение

// view1: represents view which should be hidden and from which we are starting
// view2: represents view which is second view or behind of view1
// isReverse: default if false, but if we need reverse animation we pass true and it
// will Flip from Left

func flipTransition (with view1: UIView, view2: UIView, isReverse: Bool = false) {
    var transitionOptions = UIViewAnimationOptions()
    transitionOptions = isReverse ? [.transitionFlipFromLeft] : [.transitionFlipFromRight] // options for transition

    // animation durations are equal so while first will finish, second will start
    // below example could be done also using completion block.

    UIView.transition(with: view1, duration: 1.5, options: transitionOptions, animations: {
        view1.isHidden = true
    })

    UIView.transition(with: view2, duration: 1.5, options: transitionOptions, animations: {
        view2.isHidden = false
    })
}

Вызов функции:

anim.flipTransition(with: viewOne, view2: viewTwo)
anim.flipTransition(with: viewTwo, view2: viewOne, isReverse: true)

Лучшей практикой будет создание расширения UIView и установка этой функции на это расширение, чтобы он был доступен для любого дочернего объекта UIView. Это решение также может быть написано с помощью функции завершения.

Ответ 6

Чтобы перевернуть в UIView:

  -(void) goToSeconVC
 {
  SecondVC *secondVCObj = [[SecondVC alloc] init];
  [UIView beginAnimation: @"View Flip" context: nil];
  [UIView setAnimationDuration: 1.0];
  [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
  [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight forView: self.navigationController.view cache: NO];
  [sef.navigationController pushViewController: seconVCObj animated: YES];
  [UIView commitAnimation];
 }
**To flip into a view controller:**
          viewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
         [self presentViewController:viewController animated:YES completion:nil];
**To flip out of it:**

[self dismissViewControllerAnimated:YES completion:nil];

Ответ 7

Swift 5 версия @C0mrade

func flipTransition (with view1: UIView, view2: UIView, isReverse: Bool = false) {
    var transitionOptions = UIView.AnimationOptions()
    transitionOptions = isReverse ? [.transitionFlipFromLeft] : [.transitionFlipFromRight]

    UIView.transition(with: view1, duration: 1.5, options: transitionOptions, animations: {
        view1.isHidden = true
    })

    UIView.transition(with: view2, duration: 1.5, options: transitionOptions, animations: {
        view2.isHidden = false
    })
}

Ответ 8

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.75];
// checks to see if the view is attached
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight
                       forView:flipLabel
                         cache:YES];

 flipLabel.backgroundColor = [UIColor yellowColor];



[UIView commitAnimations];

Вы можете сделать любую модификацию, которая вам нужна, когда просматриваете просмотр, Здесь я меняю цвет фона