Adds animated counting support to UILabel.

Overview

UICountingLabel

Adds animated counting support to UILabel.

alt text

CocoaPods

UICountingLabel is available on CocoaPods. Add this to your Podfile:

pod 'UICountingLabel'

And then run:

$ pod install

Setup

Simply initialize a UICountingLabel the same way you set up a regular UILabel:

UICountingLabel* myLabel = [[UICountingLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[self.view addSubview:myLabel];

You can also add it to your XIB file, just make sure you set the class type to UICountingLabel instead of UILabel and be sure to #import "UICountingLabel.h" in the header file.

Use

Set the format of your label. This will be filled with a single int or float (depending on how you format it) when it updates:

myLabel.format = @"%d";

Alternatively, you can provide a UICountingLabelFormatBlock, which permits greater control over how the text is formatted:

myLabel.formatBlock = ^NSString* (CGFloat value) {    
    NSInteger years = value / 12;
    NSInteger months = (NSInteger)value % 12;
    if (years == 0) {
        return [NSString stringWithFormat: @"%ld months", (long)months];
    }
    else {
        return [NSString stringWithFormat: @"%ld years, %ld months", (long)years, (long)months];
    }
};

There is also a UICountingLabelAttributedFormatBlock to use an attributed string. If the formatBlock is specified, it takes precedence over the format.

Optionally, set the mode. The default is UILabelCountingMethodEaseInOut, which will start slow, speed up, and then slow down as it reaches the end. Other options are described below in the Methods section.

myLabel.method = UILabelCountingMethodLinear;

When you want the label to start counting, just call:

[myLabel countFrom:50 to:100];

You can also specify the duration. The default is 2.0 seconds.

[myLabel countFrom:50 to:100 withDuration:5.0f];

Additionally, there is animationDuration property which you can use to override the default animation duration.

myLabel.animationDuration = 1.0;

You can use common convinient methods for counting, such as:

[myLabel countFromCurrentValueTo:100];
[myLabel countFromZeroTo:100];

Behind the scenes, these convinient methods use one base method, which has the following full signature:

[myLabel     countFrom:(float)startValue
                    to:(float)endValue
          withDuration:(NSTimeInterval)duration];

You can get current value of your label using -currentValue method (works correctly in the process of animation too):

CGFloat currentValue = [myLabel currentValue];

Optionally, you can specify a completionBlock to perform an acton when the label has finished counting:

myLabel.completionBlock = ^{
    NSLog(@"finished counting");
};

Formats

When you set the format property, the label will look for the presence of %(.*)d or %(.*)i, and if found, will cast the value to int before formatting the string. Otherwise, it will format it using a float.

If you're using a float value, it's recommended to limit the number of digits with a format string, such as @"%.1f" for one decimal place.

Because it uses the standard stringWithFormat: method, you can also include arbitrary text in your format, such as @"Points: %i".

Modes

There are currently four modes of counting.

UILabelCountingMethodLinear

Counts linearly from the start to the end.

UILabelCountingMethodEaseIn

Ease In starts out slow and speeds up counting as it gets to the end, stopping suddenly at the final value.

UILabelCountingMethodEaseOut

Ease Out starts out fast and slows down as it gets to the destination value.

UILabelCountingMethodEaseInOut

Ease In/Out starts out slow, speeds up towards the middle, and then slows down as it approaches the destination. It is a nice, smooth curve that looks great, and is the default method.


以下是中文教程


UILabel 添加计数动画支持.

alt text

CocoaPods

UICountingLabel 可以使用cocoaPods导入, 添加以下代码到你的Podfile文件:

pod 'UICountingLabel'

然后运行以下命令:

$ pod install

设置

初始化 UICountingLabel 的方式和普通的 UILabel是一样的:

UICountingLabel* myLabel = [[UICountingLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[self.view addSubview:myLabel];

你也可以用在 XIB 文件中, 前提是你在头文件中引入了 UICountingLabel的头文件并且使用 UICountingLabel替换掉了原生的UILabel.

使用方式

设置标签格式. 设置标签格式后,标签会在更新数值的时候以你设置的方式填充,默认是显示float类型的数值,也可以设置成显示int类型的数值,比如下面的代码:

myLabel.format = @"%d";

另外,你也可以使用 UICountingLabelFormatBlock, 这个可以对显示的文本格式进行更加高度的自定义:

// 举例:把显示的月份数变成几年零几个月的样式
myLabel.formatBlock = ^NSString* (CGFloat value) {    
    NSInteger years = value / 12;
    NSInteger months = (NSInteger)value % 12;
    if (years == 0) {
        return [NSString stringWithFormat: @"%ld months", (long)months];
    }
    else {
        return [NSString stringWithFormat: @"%ld years, %ld months", (long)years, (long)months];
    }
};

除此之外还有一个 UICountingLabelAttributedFormatBlock 用于设置属性字符串的格式,用法和上面的block类似. 如果指定了以上两个 formatBlock中的任意一个 , 它将会覆盖掉 format属性,因为block的优先级更高.

可选项, 设置动画样式. 默认的动画样式是 UILabelCountingMethodEaseInOut, 这个样式是开始时速度比较慢,然后加速,将要结束时减速. 以下将介绍其他动画样式及用法.

myLabel.method = UILabelCountingMethodLinear; // 线性变化

需要计数时只需要使用以下方法即可:

[myLabel countFrom:50 to:100];

可以指定动画的时长,默认时长是2.0秒.

[myLabel countFrom:50 to:100 withDuration:5.0f];

另外也可以使用 animationDuration 属性去设置动画时长.

myLabel.animationDuration = 1.0;

可以使用便利方法计数,例如:

[myLabel countFromCurrentValueTo:100];
[myLabel countFromZeroTo:100];

本质上,这些便利方法都是基于一个总方法封装的, 以下就是这个方法完整的声明:

[myLabel     countFrom:(float)startValue
                    to:(float)endValue
          withDuration:(NSTimeInterval)duration];

可以使用 -currentValue 方法获得当前数据, (即使在动画过程中也可以正常获得):

CGFloat currentValue = [myLabel currentValue];

可以使用 completionBlock 获得动画结束的事件:

myLabel.completionBlock = ^{
    NSLog(@"finished counting");
};

格式

当设置format属性后, 标签会检测是否有%(.*)d或者%(.*)i格式, 如果能找到, 就会将内容以int类型展示. 否则, 将会使用默认的float类型展示.

假如你需要以float类型展示, 最好设置小数点位数限制, 例如使用@"%.1f"来限制只显示一位小数.

因为使用了标准的stringWithFormat:方法, 可以按照自己的意愿自定义格式,例如:@"Points: %i".

动画类型

当前有四种技术动画样式.

UILabelCountingMethodLinear

匀速计数动画.

UILabelCountingMethodEaseIn

开始比较缓慢,快结束时加速,结束时突然停止.

UILabelCountingMethodEaseOut

开始速度很快,快结束时变得缓慢.

UILabelCountingMethodEaseInOut

开始时比较缓慢,中间加速,快结束时减速.动画速度是一个平滑的曲线,是默认采用的动画样式。

Comments
  • Single Workspace Carthage Support + Project Rearrangement

    Single Workspace Carthage Support + Project Rearrangement

    This PR rearranges the project to match the same layout generated via pod lib create, meaning the example & library projects are on a single workspace (& should work via pod try as well) - that in turn should address the issues highlighted in #38. On the example project, I've also modernised the XIB (simply by opening it in Xcode 11), created a basic launch storyboard matching your old launch images & nudged the UI elements down by 20 pixels to cater for notches.

    A positive (& intended) side effect of this is this adds Carthage support via the _Pods.xcodeproj project on the root directory, and I've tested this for both iOS & tvOS.

    opened by SimonRice 5
  • Drop-in conversion to Swift 4+

    Drop-in conversion to Swift 4+

    • It keeps the exact same public objc interface as before, so CTPViewController.m works without a single character change.
    • it's compatible Swift 3, Swift 4, Swift 4.2 and Swift 5.0.
    opened by Coeur 4
  • Expose `-setTextValue:` for subclasses

    Expose `-setTextValue:` for subclasses

    This exposes the -setTextValue: method for the purpose of subclassing.

    I had a case where the value to animate wasn't a simple value. It was a "months" count, but once you hit 12 months it had to flip over to years and months, so:

    • 10 months
    • 11 months
    • 1 year
    • 1 year 1 month
    • 1 year 2 months
    • etc

    UICountingLabel provides an excellent framework for making things go, especially the animation curves -- I just needed to easily set the text value. I can pass in the total count of months, I just need to then format the text differently. So subclassing works, but I needed -setTextValue: to be exposed in the header so I could override it.

    I opted to just make the category in the main .h file because it avoided the need to modify the podspec. Often people approach this by having something like a UICountingLabel_Subclasses.h type of file that then exposes those things. Same issue in the end, but a little clearer and if someone wants to subclass they do need to explicitly #import the right file -- tho perhaps less critical now given I'm using Cocoapods, Swift, and thus frameworks/modules.

    If there's another approach you'd like to take to support this, I'm open to alternatives that work better for the distribution.

    Thank you.

    opened by hsoi 4
  • Replacing Wall Clock with Monotonic Clock

    Replacing Wall Clock with Monotonic Clock

    Replacing Wall Clock with Monotonic Clock to prevent negative progress when there are leap seconds or timezone changes.

    For reference, here are classic solutions for Monotonic (and reliable) time progression:

    • mach_absolute_time() from Darwin, but requires conversion to seconds with mach_timebase_info
    • ProcessInfo.processInfo.systemUptime from Foundation, open-source wrapper on mach_absolute_time() giving directly a number of seconds
    • DispatchTime.now() from Dispatch, open-source wrapper on mach_absolute_time() giving easily a number of seconds
    • CACurrentMediaTime() from QuartzCore, close-source wrapper giving directly a number of seconds, and what Apple uses for animations: https://www.google.com/search?q=CACurrentMediaTime+site%3Aopensource.apple.com

    And here are classic solutions for Wall clocks (totally unreliable! for timing) which are affected by leap seconds, timezone changes, winter/summer hour changes, any manual user change on the system clock:

    • gettimeofday() in POSIX standard
    • DispatchWallTime.now() from Dispatch
    • CFAbsoluteTimeGetCurrent() from CoreFoundation
    • Date()/NSDate() from Foundation and any of its methods (including timeIntervalSinceReferenceDate)
    opened by Coeur 3
  • Add common convenient methods (such as -currentValue) + performance improvements

    Add common convenient methods (such as -currentValue) + performance improvements

    I've added a few common convenient methods, such as the ability to get label's current value at any given point of time (even in the process of animating). You can now set default animation duration as a property for the label instead of using 2 seconds or sending a magic number each time you want the label to animate.

    Also, obvious CPU performance issue has been fixed — now if you ask a label to count to another value while it is still in the animating state, old timer gets invalidated before creating a new one.

    P.S. Thank you for this handy class. 👍

    opened by rinatkhanov 3
  • Any plans to update podspec to include UICountingLabelAttributedFormatBlock changes?

    Any plans to update podspec to include UICountingLabelAttributedFormatBlock changes?

    I love UICountingLabel and would really like to use it with attributed strings. Is the code for UICountingLabelAttributedFormatBlock stable enough to update podspec?

    opened by thrillyb 3
  • Handle 0s durations

    Handle 0s durations

    If you call countFrom: with a duration of 0 the label's value is mangled – along the way a divide-by-zero happens that seems to find its way in.

    It should probably be the caller's problem to make sure they aren't sending 0, but this way they won't have to worry!

    opened by adamaveray 3
  • Fix label not counting while UI Updates happening

    Fix label not counting while UI Updates happening

    NSTimers don't fire when user interface updates are happening, so the label will appear to skip numbers when embedded in something like a scroll view that's scrolling. This changes from NSDefaultRunLoopMode to NSRunLoopCommonModes, which includes events coming in from the UI during scrolling, allowing the timer to continue to animate.

    opened by awebermatt 3
  • Unable to update pod version to 1.4.1

    Unable to update pod version to 1.4.1

    The pod file does not find the newest version of it

    [!] Unable to satisfy the following requirements:
    
    - `UICountingLabel (~> 1.4.1)` required by `Podfile`
    
    None of your spec sources contain a spec satisfying the dependency: `UICountingLabel (~> 1.4.1)`.
    
    You have either:
     * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`.
     * mistyped the name or version.
     * not added the source repo that hosts the Podspec to your Podfile.
    
    Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by default.
    
    opened by dyegos 2
  • Updated to iOS 7.0 min deployment target

    Updated to iOS 7.0 min deployment target

    fix: removing a warning in a block declaration feat: updated deployment target to iOS 7.0 (minimum to build without errors with Xcode 9) feat: updated podspec's deployment target to iOS 7.0 (as Xcode's project)

    When using this pod with a minimum target of iOS 10.0 and Xcode 9, the pod has 2 warnings, one about the block declaration not being a prototype. The other one about setAttributedText: which is only available in iOS 6.0 or newer.

    opened by jdev7 2
  • Documentation update

    Documentation update

    Per https://github.com/dataxpress/UICountingLabel/pull/42#issuecomment-163097616 :smile_cat:

    Fleshing out the documentation to cover the format blocks and the completion block.

    opened by hsoi 2
  • Is it supporting swift 4.2? Not able to access.

    Is it supporting swift 4.2? Not able to access.

    leadsCountingLabel.method = UILabelCountingMethodEaseIn --- (Error: Use of unresolved identifier 'UILabelCountingMethodEaseIn'; did you mean 'UILabelCountingMethod'?)

    opened by Iammahiiii 1
  • Add support for locale based thousands separators

    Add support for locale based thousands separators

    If it's a number over 1,000 it would be nice to add a thousands separator based on locale. Not a must have but just noticed it. Great Library BTW. Thanks for the hard work!

    opened by nickthedude 0
Releases(1.4.1)
Owner
Tim Gostony
Tim Gostony
UILabel drop-in replacement supporting Hashtags

ActiveLabel.swift UILabel drop-in replacement supporting Hashtags (#), Mentions (@), URLs (http://), Emails and custom regex patterns, written in Swif

Optonaut 4.2k Dec 31, 2022
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Atributika is an easy and painless way to build NSAttributedString. It is able to detect HTML-like tags, links, phone numbers, hashtags, any regex or

Pavel Sharanda 1.1k Dec 26, 2022
Simple countdown UILabel with morphing animation, and some useful function.

CountdownLabel Simple countdown UILabel with morphing animation, and some useful function. features Simple creation Easily get status of countdown fro

keishi suzuki 903 Dec 29, 2022
Glitching UILabel for iOS 📺

Glitching UILabel for iOS ?? Created by Lee Sun-Hyoup. Try the sample $ pod try GlitchLabel Requirements iOS 8.0+ Swift 3 Xcode 8 Installation CocoaP

Lee Sun-Hyoup 1k Dec 14, 2022
Incrementable UILabel for iOS and tvOS

IncrementableLabel IncrementableLabel is the easiest way to have incrementable numbers in an UILabel! Usage let myIncrementableLabel = IncrementableLa

Tom Baranes 81 Feb 4, 2022
KDEDateLabel is an UILabel subclass that updates itself to make time ago's format easier.

KDEDateLabel KDEDateLabel is an UILabel subclass that saves you from refreshing it when using 'time ago' format. Installation You have multiple choice

Kevin Delannoy 117 May 16, 2022
A morphing UILabel subclass written in Swift.

LTMorphingLabel A morphing UILabel subclass written in Swift. The .Scale effect mimicked Apple's QuickType animation of iOS 8 of WWDC 2014. New morphi

Lex Tang 7.9k Jan 4, 2023
UILabel with image placed from left or right

SMIconLabel UILabel with possibility to place small icon on the left or on the right side. Take a look at preview image or build sample app to see how

Anatoliy Voropay 94 Apr 27, 2022
A handy class for iOS to use UILabel as a countdown timer or stopwatch just like in Apple Clock App.

MZTimerLabel Purpose MZTimerLabel is a UILabel subclass, which is a handy way to use UILabel as a countdown timer or stopwatch just like that in Apple

Mines Chan 1.6k Dec 14, 2022
A drop-in replacement for UILabel that supports attributes, data detectors, links, and more

TTTAttributedLabel A drop-in replacement for UILabel that supports attributes, data detectors, links, and more TTTAttributedLabel is a drop-in replace

TTTAttributedLabel 8.8k Dec 30, 2022
UILabel subclass, which additionally allows shadow blur, inner shadow, stroke text and fill gradient.

THLabel THLabel is a subclass of UILabel, which additionally allows shadow blur, inner shadow, stroke text and fill gradient. Requirements iOS 4.0 or

Tobias Hagemann 654 Nov 27, 2022
UILabel replacement with fine-grain appear/disappear animation

ZCAnimatedLabel UILabel-like view with easy to extend appear/disappear animation Features Rich text support (with NSAttributedString) Group aniamtion

Chen 2.3k Dec 5, 2022
MTLLinkLabel is linkable UILabel. Written in Swift.

# MTLLinkLabel is linkable UILabel. Written in Swift. Requirements iOS 8.0+ Xcode 7.3+ Installation Carthage You can install Carthage with Homebrew. $

Recruit Holdings. Media Technology Lab 74 Jul 1, 2022
A simple designable subclass on UILabel with extra IBDesignable and Blinking features.

JSLabel Demo pod try JSLabel ...or clone this repo and build and run/test the JSLabel project in Xcode to see JSLabel in action. If you don't have Coc

Jogendra 6 May 9, 2022
🔥 🔥 🔥Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

?? ?? ??Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

null 60 Dec 12, 2022
Gifu adds protocol-based, performance-aware animated GIF support to UIKit.

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Reda Lemeden 2.8k Jan 7, 2023
JustPeek is an iOS Library that adds support for Force Touch-like Peek and Pop interactions on devices that do not natively support this kind of interaction.

JustPeek Warning: This library is not supported anymore by Just Eat. JustPeek is an iOS Library that adds support for Force Touch-like Peek and Pop in

Just Eat 68 Apr 4, 2021
A simple Swift package for counting the Syllables in a sentence.

A simple Swift package for counting the Syllables in a sentence.

null 2 Jan 3, 2022
Challenge... counting game for kids... should be entertaining, educational and fun... o_O

MultiTainment Simple multiplication game for kids. Possible to choose how many questions they want to answer and how hard shoud it be. Simple funny in

Pavel Surový 0 Dec 4, 2021
Cardshark is an iOS card counting App that uses state of the art machine learning (YOLO) to classify and count the cards at real time.

Cardshark The game of Blackjack is one of the most popular casino games in the world. It is also the most winnable using a skill called Card Counting.

Eric Miao 1 Jan 23, 2022