Animate Uilabel Text Between Two Numbers

Animate UILabel text between two numbers?

You can use the automatic transitions. It's working perfectly well :

// Add transition (must be called after myLabel has been displayed)
CATransition *animation = [CATransition animation];
animation.duration = 1.0;
animation.type = kCATransitionFade;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[myLabel.layer addAnimation:animation forKey:@"changeTextTransition"];

// Change the text
myLabel.text = newText;

This code works if myLabel is already displayed. If not myLabel.layer will be nil and the animation will not be added to the object.


in Swift 4 that would be:

let animation: CATransition = CATransition()
animation.duration = 1.0
animation.type = kCATransitionFade
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
myLabel.layer.add(animation, forKey: "changeTextTransition")

How to Animate uilabel text between 3 values

Use the NStimer for changing the text

in .h file

@interface ViewController : UIViewController
{
NSTimer * timer;
UILabel * downloadingLbl;
}

and in .m file

- (void)viewDidLoad
{
[super viewDidLoad];

downloadingLbl.text = @"Downloading.";
if (!timer) {
timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
}
}

-(void)onTick:(NSTimer*)timer
{
NSLog(@"Tick...");

if ([downloadingLbl.text isEqualToString:@"Downloading."]) {
downloadingLbl.text = @"Downloading..";
} else if ([downloadingLbl.text isEqualToString:@"Downloading.."]) {
downloadingLbl.text = @"Downloading...";
} else if ([downloadingLbl.text isEqualToString:@"Downloading..."]) {
downloadingLbl.text = @"Downloading.";
}
}

And when your download complete that make timer invalidate.

[timer invalidate];

Animate text change in UILabel

Here is the code to make this work.

[UIView beginAnimations:@"animateText" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:1.0f];
[self.lbl setAlpha:0];
[self.lbl setText:@"New Text";
[self.lbl setAlpha:1];
[UIView commitAnimations];

Repeat Fade In / Fade Out Between Two Different Texts On Same UILabel

Try with this class:

import UIKit

@IBDesignable class FadingLabel: UILabel
{
// The secondary text
@IBInspectable var secondaryText:String?
var primaryText:String?

// Animation time, is divided by 2
@IBInspectable var animationTime:TimeInterval = 1

// Set this flag to true to stop animation
var stop = true

// Start the animation
func startAnimating()
{
stop = false
if primaryText == nil
{
primaryText = self.text
}

fadeAnim()
}

// Stop the animation
func stopAnimating(_ sender: UIButton)
{
stop = true
}

@objc private func fadeAnim()
{
if stop
{
return
}

// Fade out
UIView.animate(withDuration: animationTime / 2, animations: {
self.alpha = 0
}) { (complete) in
UIView.animate(withDuration: self.animationTime / 2, animations: {
if self.text == self.primaryText
{
self.text = self.secondaryText
}
else
{
self.text = self.primaryText
}

self.alpha = 1

}, completion: { (complete2) in
self.fadeAnim()
})
}
}
}

Usage:

  • put a label in your view controller;
  • set the label class to FadingLabel;
  • set the secondary text and the animation time in the storyboard inspector
  • call the methods startAnimating or stopAnimating as needed.

Animate UILabel with numbers

I took the code from the post sergio suggested you look at, but took note of Anshu's mention that you wanted a moving up and down animation rather then a fade-in/fade-out animation, so I changed the code to fit what you wanted. Here you go:

// Add transition (must be called after myLabel has been displayed)
CATransition *animation = [CATransition animation];
animation.duration = 1.0; //You can change this to any other duration
animation.type = kCATransitionMoveIn; //I would assume this is what you want because you want to "animate up or down"
animation.subtype = kCATransitionFromTop; //You can change this to kCATransitionFromBottom, kCATransitionFromLeft, or kCATransitionFromRight
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[myLabel.layer addAnimation:animation forKey:@"changeTextTransition"];

// Change the text
myLabel.text = newText;

Hope this helps!

How to animate incrementing number in UILabel

You could use a flag to see if it has to go up or down.
Instead of a for loop, use a while loop.
In this way, you are creating a loop that keeps going, so you have to find a way to stop it also, f.e. by a button press.

Update UILabel text animated

Sure, you can update it "animated", but you have to use a repeating timer, and add one (or whatever interval you want) to the count each time the timer's selector is called. Include a test for the final value, and invalidate the timer when you get there.

After Edit:

If you want the speed of the count to slow down toward the end, I wouldn't use a timer, I would use performSelector:withObject:afterDelay:. To make it repeat, you would call this method from within its selector. You would need to do some test to see if you're near the end of the count up, and then add a little bit of time to the delay with each pass. Something like this:

-(IBAction)countUp:(id)sender {
[self performSelector:@selector(countUpLabel) withObject:nil afterDelay:.1];
}

-(void)countUpLabel {
static float delay = .01;
num+= 1;
label.text = [NSString stringWithFormat:@"%d",num];
if (num < 40) {
[self performSelector:@selector(countUpLabel) withObject:nil afterDelay:.1];
}else if (num > 35 && num <50) {
[self performSelector:@selector(countUpLabel) withObject:nil afterDelay:.1 + delay];
delay += 0.01;
}
}

How to animate UILabel text size (and color)

As I mentioned, applying a CGAffineTransform to a UILabel to scale it is frustrating for design-oriented developers, for two reasons.

  1. The transform doesn't account for tracking and font variants. San Francisco (Apple's system font) uses two distinct variants of its font depending on the text size.

iOS automatically applies the most appropriate variant based on the point size and the user's accessibility settings. Adjust tracking—the spacing between letters—appropriately.

SF Pro Text is applied to text 19 points or smaller, while SF Pro Display is applied to text 20 points or larger. Each variant has different "tracking" values — the spacing between letters — for each point size (see: the many tracking values under Font Usage and Tracking).

Unfortunately, CGAffineTransform doesn't set a new pointSize, which would otherwise force a redraw of the view. Applying a transform just scales the rasterized bitmap of the UILabel, which means that fonts and tracking values aren't adaptive. So, if we're scaling our label by 2.0 from 10pt to 20pt, our resulting UILabel at 20pt will still be using SF Pro Text with 12pt tracking, instead of SF Pro Display with 19pt tracking. You can see below that the red label is transformed and hence does not adjust its font.


  1. Transforming a view or layer leads to blurriness. As previously alluded to, Core Graphics doesn't re-render the view, but rather transforms the view's 2D map of pixels. The red label below is clearly blurry.

The Solution

Our best bet is to use CATextLayer instead of UILabel, which Apple says is:

A layer that provides simple text layout and rendering of plain or attributed strings.

The CATextLayer docs list var string: Any?, var font: CFTypeRef?, var fontSize: CGFloat, var foregroundColor: CGColor? and more as properties, which most of the time is all we need. Perfect!

All we need to do is add a CAPropertyAnimation — like CABasicAnimation — to the CATextLayer to animate its properties, like so:

// Create the CATextLayer
let textLayer = CATextLayer()
textLayer.string = "yourText"
textLayer.font = UIFont.systemFont(ofSize: startFontSize)
textLayer.fontSize = startFontSize
textLayer.foregroundColor = UIColor.black.cgColor
textLayer.contentsScale = UIScreen.main.scale
textLayer.frame = view.bounds
view.layer.addSublayer(textLayer)

// Animation
let duration: TimeInterval = 10
textLayer.fontSize = endFontSize
let fontSizeAnimation = CABasicAnimation(keyPath: "fontSize")
fontSizeAnimation.fromValue = startFontSize
fontSizeAnimation.toValue = endFontSize
fontSizeAnimation.duration = duration
textLayer.add(fontSizeAnimation, forKey: nil)

and voila! The black text below is our properly scaled CATextLayer. Sharp and with the correct font variant.

Alt Text

h/t to Yinan for the code: https://stackoverflow.com/a/42047777/4848310. Yinan also discusses how to use CATextLayer with Auto Layout constraint-based animations.


Bonus! This also works for animating text color! Just use the foregroundColor property.

UILabel to animate left and back again from right


pod MarqueeLabel

MarqueeLabel provide this feature. Just set the class name of your label to MarqueeLabel as below:-

@IBOutlet weak var lblLocation: MarqueeLabel!

Set the properties according to your requirement:-

  1. Duration
  2. FadeLength
  3. MarqueeType


Related Topics



Leave a reply



Submit