Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Animations with UILabel

Tags:

ios

I've an array that includes 4 values which will be presented with 2 different UILabel. I'll group the values in pairs. In a specific second the label changes value with another item of pair recursively.

If it's possible, I want to give an animation something like fade out or maybe slide left/right effect.

I've looked some contents already, but nothing meant to me. For example here is a working animation (according to accepted answer):

[UIView animateWithDuration:1.0 delay:0.f options:(UIViewAnimationOptionAutoreverse| UIViewAnimationOptionRepeat)
   animations:^{
   playerScore.alpha=1.f;
   } completion:^(BOOL finished){
   playerScore.alpha=0.f;
   }];

I'm not sure where to put this code, in a seperate method or in viewDidLoad. Can anyone give clues and information? It would be great.

like image 646
Newbie iOS Developer Avatar asked Aug 31 '12 10:08

Newbie iOS Developer


2 Answers

it is not clear for me why you need so many UILabel because you can add transition animations when i.e. you change the text in the current UILabel.

UILabel *textLabel = // ... whatever

[textLabel setText:@"Initial text what I just write accidentally"];

CATransition *transitionAnimation = [CATransition animation];
[transitionAnimation setType:kCATransitionFade];
[transitionAnimation setDuration:0.3f];
[transitionAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[transitionAnimation setFillMode:kCAFillModeBoth];
[textLabel.layer addAnimation:transitionAnimation forKey:@"fadeAnimation"];

[textLabel setText:@"New text will show after a nice fade effect"];

it is very elegant and easy solution.


UPDATE (on 6 Jan 2016)

NOTE: the animation will be removed automatically after it is completed (or cancelled, or failed, or whatever), and you need to be aware of regenerating the animation for every session or keeping the current animation alive explicitly by setting the removedOnCompletion property to FALSE or NO.

like image 163
holex Avatar answered Nov 04 '22 14:11

holex


Swift version of @holex answer:

textLabel.text = "originalValue"

let textAnimation = CATransition()
textAnimation.type = kCATransitionFade
textAnimation.duration = 0.4

textLabel.layer.addAnimation(textAnimation, forKey: nil)
textLabel.text = "newValue"

If you'd like a callback for when the animation completes, use the following:

CATransaction.begin()
CATransaction.setCompletionBlock({
     print("Text Animation Complete!")
})

let textAnimation = CATransition()
textAnimation.type = kCATransitionFade
textAnimation.duration = 0.4

textLabel.layer.addAnimation(textAnimation, forKey: nil)
textLabel.text = "newValue"

CATransaction.commit()
like image 42
RanLearns Avatar answered Nov 04 '22 12:11

RanLearns