Newbie iOS Developer
Newbie iOS Developer

Reputation: 395

Using Animations with UILabel

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.

Upvotes: 10

Views: 8467

Answers (2)

holex
holex

Reputation: 24041

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.

Upvotes: 15

RanLearns
RanLearns

Reputation: 4166

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()

Upvotes: 1

Related Questions