Pergunta

O que é considerado as melhores práticas para animar as transições de visualização no iPhone?

Por exemplo, o ViewTransitions Projeto de amostra da Apple usa código como:

CATransition *applicationLoadViewIn = [CATransition animation];
[applicationLoadViewIn setDuration:1];
[applicationLoadViewIn setType:kCATransitionReveal];
[applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[[myview layer] addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];

Mas também existem trechos de código flutuando pela rede que se parecem com o seguinte:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.75];
[UIView setAnimationDelegate:self];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myview cache:YES];
[myview removeFromSuperview];
[UIView commitAnimations];

Qual é a melhor abordagem? Se você pudesse fornecer um trecho também, seria muito apreciado.

NOTA: Não consegui obter a segunda abordagem para funcionar corretamente.

Foi útil?

Solução

De Referência UIViewseção sobre o beginAnimations:context: método:

O uso desse método é desencorajado no iPhone OS 4.0 e posterior. Você deve usar os métodos de animação baseados em blocos.

Por exemplo, de animação baseada em bloco com base no comentário de Tom

[UIView transitionWithView:mysuperview 
                  duration:0.75
                   options:UIViewAnimationTransitionFlipFromRight
                animations:^{ 
                    [myview removeFromSuperview]; 
                } 
                completion:nil];

Outras dicas

Eu tenho usado o último para muitas animações leves agradáveis. Você pode usá -lo Crossfade duas visualizações, ou desaparecer uma na frente de outra, ou desbotar -se. Você pode atirar em uma vista sobre outro como um banner, você pode fazer uma visão de alongamento ou encolher ... Estou recebendo muita milhagem beginAnimation/commitAnimations.

Não pense que tudo o que você pode fazer é:

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myview cache:YES];

Aqui está uma amostra:

[UIView beginAnimations:nil context:NULL]; {
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationDelegate:self];
    if (movingViewIn) {
// after the animation is over, call afterAnimationProceedWithGame
//  to start the game
        [UIView setAnimationDidStopSelector:@selector(afterAnimationProceedWithGame)];

//      [UIView setAnimationRepeatCount:5.0]; // don't forget you can repeat an animation
//      [UIView setAnimationDelay:0.50];
//      [UIView setAnimationRepeatAutoreverses:YES];

        gameView.alpha = 1.0;
        topGameView.alpha = 1.0;
        viewrect1.origin.y = selfrect.size.height - (viewrect1.size.height);
        viewrect2.origin.y = -20;

        topGameView.alpha = 1.0;
    }
    else {
    // call putBackStatusBar after animation to restore the state after this animation
        [UIView setAnimationDidStopSelector:@selector(putBackStatusBar)];
        gameView.alpha = 0.0;
        topGameView.alpha = 0.0;
    }
    [gameView setFrame:viewrect1];
    [topGameView setFrame:viewrect2];

} [UIView commitAnimations];

Como você pode ver, você pode brincar com alfa, molduras e até tamanhos de vista. Brincar. Você pode se surpreender com seus recursos.

A diferença parece ser a quantidade de controle que você precisa sobre a animação.

o CATransition A abordagem oferece mais controle e, portanto, mais coisas a serem configuradas, por exemplo. a função de tempo. Sendo um objeto, você pode armazená -lo para mais tarde, refatorar para apontar todas as suas animações para reduzir o código duplicado, etc.

o UIView Os métodos de classe são métodos de conveniência para animações comuns, mas são mais limitadas do que CATransition. Por exemplo, existem apenas quatro tipos de transição possíveis (flip para a esquerda, vire para a direita, enrole -se, enrole para baixo). Se você quisesse fazer um desbotamento, teria que cavar CATransition's desvanecer a transição, ou estabelecer uma animação explícita de seu UIViewAlpha.

Observe que CATransition no Mac OS X permitirá que você especifique um arbitrário CoreImage filtrar para usar como uma transição, mas como está agora você não pode fazer isso no iPhone, que não tem CoreImage.

Podemos animar imagens no iOS 5 usando este código simples.

CGRect imageFrame = imageView.frame;
imageFrame.origin.y = self.view.bounds.size.height;

[UIView animateWithDuration:0.5
    delay:1.0
    options: UIViewAnimationCurveEaseOut
    animations:^{
        imageView.frame = imageFrame;
    } 
    completion:^(BOOL finished){
        NSLog(@"Done!");
    }];

No UIView documentos, leia sobre esta função para iOS4+

+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion

De qualquer forma, o método "Block" é preferido hoje em dia. Vou explicar o bloco simples abaixo.

Considere os cortados abaixo. Bug2 e Bug 3 são visualizações de imagem. A animação abaixo descreve uma animação com 1 segunda duração após um atraso de 1 segundo. O BUG3 é movido do centro para o centro do BUG2. Depois que a animação for concluída, ela será registrada "Center Animation Coned!".

-(void)centerAnimation:(id)sender
{
NSLog(@"Center animation triggered!");
CGPoint bug2Center = bug2.center;

[UIView animateWithDuration:1
                      delay:1.0
                    options: UIViewAnimationCurveEaseOut
                 animations:^{
                     bug3.center = bug2Center;
                 } 
                 completion:^(BOOL finished){
                     NSLog(@"Center Animation Done!");
                 }];
}

Espero que esteja limpo !!!

Encontrei um bom tutorial neste link. Espero que isso seja útil para alguém.

Uiview-animação-tutorial

Aqui está o código para animação suave, pode ser útil para muitos desenvolvedores.
Encontrei este trecho de código deste tutorial.

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[animation setAutoreverses:YES];
[animation setFromValue:[NSNumber numberWithFloat:1.3f]];
[animation setToValue:[NSNumber numberWithFloat:1.f]];
[animation setDuration:2.f];
[animation setRemovedOnCompletion:NO];

[animation setFillMode:kCAFillModeForwards];
[[self.myView layer] addAnimation:animation forKey:@"scale"];/// add here any Controller that you want t put Smooth animation.

Vamos tentar fazer o checkout para o Swift 3 ...

UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: {
    myview.removeFromSuperview()
}, completion: nil)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top