web-dev-qa-db-fra.com

Meilleures pratiques d'animation iPhone UIView

Quelle est la meilleure pratique pour animer les transitions de vue sur l'iPhone?

Par exemple, l'exemple de projet ViewTransitions de Apple utilise un code tel que:

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

mais il y a aussi des extraits de code flottant autour du réseau qui ressemblent à ceci:

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

Quelle est la meilleure approche? Si vous pouviez aussi fournir un extrait, ce serait très apprécié.

NOTE: Je n'ai pas réussi à faire fonctionner correctement la deuxième approche.

142
Keith Fitzgerald

Dans la section référence UIView sur la méthode beginAnimations:context::

L'utilisation de cette méthode est déconseillée dans iPhone OS 4.0 et versions ultérieures. Vous devez plutôt utiliser les méthodes d'animation basées sur des blocs.

Par exemple, une animation basée sur des blocs basée sur le commentaire de Tom

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

J'ai utilisé ce dernier pour beaucoup d'animations légères Nice. Vous pouvez l’utiliser en fondu enchaîné sur deux vues, ou en fondu enchaîné, ou en fondu enchaîné. Vous pouvez prendre une vue par-dessus une autre comme une bannière, vous pouvez agrandir ou réduire une vue ... Je tire beaucoup de kilomètres de beginAnimation/commitAnimations.

Ne pensez pas que tout ce que vous pouvez faire, c'est:

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

Voici un échantillon:

[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];

Comme vous pouvez le constater, vous pouvez jouer avec des images alpha, des cadres et même des tailles de vues. S'amuser. Vous pourriez être surpris par ses capacités.

69
mahboudz

La différence semble être la quantité de contrôle dont vous avez besoin sur l'animation.

L'approche CATransition vous donne plus de contrôle et donc plus de choses à configurer, par exemple. la fonction de chronométrage. Étant un objet, vous pouvez le stocker pour plus tard, un refactor pour y pointer toutes vos animations afin de réduire le code dupliqué, etc.

Les méthodes de la classe UIView sont des méthodes pratiques pour les animations courantes, mais sont plus limitées que CATransition. Par exemple, il n'y a que quatre types de transition possibles (basculer à gauche, basculer à droite, se recroqueviller, se recourber). Si vous souhaitez créer un fondu entrant, vous devez soit creuser jusqu'à la transition _CATransition's_, ou créer une animation explicite de l'alpha de votre UIView.

Notez que CATransition sous Mac OS X vous permettra de spécifier un filtre CoreImage à utiliser comme transition, mais dans l'état actuel des choses, vous ne pouvez pas le faire sur l'iPhone, qui manque de CoreImage.

52
Ryan McCuaig

Nous pouvons animer des images dans iOS 5 en utilisant ce code simple.

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!");
    }];
26
Guru

Dans la documentation UIView, consultez cette fonction pour ios4 +

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

Quoi qu'il en soit, la méthode "Block" est préférée de nos jours. Je vais expliquer le bloc simple ci-dessous.

Considérons le coupé ci-dessous. bug2 et bug 3 sont imageViews. L'animation ci-dessous décrit une animation d'une durée de 1 seconde après un délai de 1 seconde. Le bug3 est déplacé de son centre vers le centre de bug2. Une fois l'animation terminée, elle sera enregistrée "Center Animation Done!".

-(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!");
                 }];
}

J'espère que c'est propre !!!

6
Deepukjayan

J'ai trouvé un bon tutoriel dans ce lien. J'espère que cela sera utile pour quelqu'un.

iview-animation-tutorial

4
Dilip Rajkumar

Voici le code pour une animation fluide, pourrait être utile pour de nombreux développeurs.
J'ai trouvé cet extrait de code de ce tutoriel.

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.
2
iPatel

essayons et payons Pour Swift 3 ...

UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: {
    myview.removeFromSuperview()
}, completion: nil)
2
Saurabh Sharma