Giter VIP home page Giter VIP logo

uicountinglabel's Introduction

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

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

uicountinglabel's People

Contributors

adamaveray avatar awebermatt avatar coeur avatar danielbowden avatar dataxpress avatar guozhiqiang avatar hsoi avatar jdev7 avatar jesseclay avatar lazarev avatar nemesis avatar onekiloparsec avatar rinatkhanov avatar simonbs avatar simonrice avatar thunderrabbit avatar williammorrisssc avatar yulin0629 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uicountinglabel's Issues

add animation effect

I was hoping for an odometer effect like this
http://github.hubspot.com/odometer/api/themes/

it seems like using kCATransitionFromBottom this should be possible.

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

    // Change the text
    _instructions.text = @"127";

Remove string `format` property, replace with `setFormat:` method

Instead of having a separate NSString* format, only expose the formatBlock property, and make a setFormat: method that sets up the right format block only at set time instead of on every iteration.

This will ultimately improve performance, as a single block call each time is much faster than regular expression searches every frame.

So, it would look something like:

-(void)setFormat:(NSString*)format
{
    self.formatBlock = ^(NSString*) ^(float val) {
        return [NSString stringWithFormat:format,val];   
    };
}

Note - something will have to deal with formats that pass in %d or %i (as the current regex does) - perhaps find these and then cast to int if it has those? maybe two different blocks? just ideas

Add support for larger numbers

First of all, great library :)

The only thing I'd ask for is support for numbers (ie. NSDecimalNumber) with a higher value than the float max.

[self.barChart strokeChart]; creates EXE_BAD_ACCESS

I just updated to this latest build and when I call the [self.barChart strokeChart]; it gives EXE_BAD_EXEC error in below line:

PNBarChart.m file

- (void)strokeChart
{
    [self viewCleanupForCollection:_labels];
    ......
    //Add y labels

        float yLabelSectionHeight = (self.frame.size.height - _chartMargin * 2 - xLabelHeight) / _yLabelSum;

        for (int index = 0; index < _yLabelSum; index++) {

            // This line causes the EXE_BAD_ACCESS
            NSString *labelText = _yLabelFormatter((float)_yValueMax * ( (_yLabelSum - index) / (float)_yLabelSum )); // CAUSES ERROR EXE_BAD_ACCESS

Any ideas?

provide method to initialize counter

Hi

This is a very useful pod. I wasn't able to figure out how to initialize the counter to something other than 0. Right now my viewDidLoad has
[self.myLabel countFrom:123 to:123 withDuration:0.0f ];
as an example to initialize to 123.

The currentValue property doesn't have associated get/set options.
(I could also be making a silly mistake, I'm somewhat new to iOS and objective C)

Cocoapods

I second that emotion. Going to give you credit in our app definitely.

formatBlock crashes with EXC_BAD_ACCESS on Swift

After importing UICountingLabel into a Swift project, setting format works as expected:

myLabel.format = "$%d asdf" // This works

I then attempt to set formatBlock:

totalDebtLabel.formatBlock = {(debtValue) -> String in
    let returnString = "$\(debtValue) asdf"
    return returnString
}

I expect this to work similarly, but instead I get an EXC_BAD_ACCESS crash:

* thread #1: tid = 0x123f44, 0x01f500be libobjc.A.dylib`objc_msgSend + 26, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x22281)
    frame #0: 0x01f500be libobjc.A.dylib`objc_msgSend + 26
    frame #1: 0x01f50eb1 libobjc.A.dylib`objc_release + 65
  * frame #2: 0x000edc05 ExampleApp`reabstraction thunk helper from @callee_owned (@unowned Swift.Float) -> (@owned Swift.ImplicitlyUnwrappedOptional<Swift.String>) to @callee_unowned @objc_block (@unowned Swift.Float) -> (@autoreleased Swift.ImplicitlyUnwrappedOptional<ObjectiveC.NSString>) + 229 at ViewController.swift:31
    frame #3: 0x00122dfc ExampleApp`-[UICountingLabel setTextValue:](self=0x7a099390, _cmd=0x00129f4e, value=20.8544655) + 348 at UICountingLabel.m:204
    frame #4: 0x00122bfd ExampleApp`-[UICountingLabel updateValue:](self=0x7a099390, _cmd=0x00129fe9, timer=0x79ece300) + 621 at UICountingLabel.m:190
    frame #5: 0x00957819 Foundation`__NSFireTimer + 97
    frame #6: 0x002990b6 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 22
    frame #7: 0x00298a3d CoreFoundation`__CFRunLoopDoTimer + 1309
    frame #8: 0x00257e6a CoreFoundation`__CFRunLoopRun + 2090
    frame #9: 0x0025737b CoreFoundation`CFRunLoopRunSpecific + 443
    frame #10: 0x002571ab CoreFoundation`CFRunLoopRunInMode + 123
    frame #11: 0x04f382c1 GraphicsServices`GSEventRunModal + 192
    frame #12: 0x04f380fe GraphicsServices`GSEventRun + 104
    frame #13: 0x00d6c0c6 UIKit`UIApplicationMain + 1526
    frame #14: 0x000f02ee ExampleApp`top_level_code + 78 at AppDelegate.swift:12
    frame #15: 0x000f032b ExampleApp`main + 43 at AppDelegate.swift:0
    frame #16: 0x026aaac9 libdyld.dylib`start + 1

I attempted to debug the problem using image lookup --address and the Zombie profiler, but didn't find anything interesting.

Has anyone been able to get this to work with the @"%d" format, or showing a float with no decimal values?

All I want to do is count from a value like 0 to 38. I don't want to display any decimal points or numbers after a decimal point. Just want a simple number like "38" or "500".

Is anyone successfully doing this? If I set my format to @"%d", the label counts up weird and stops at the wrong value. I have tried hacking around in the repo and using formatted strings but nothing seems to work.

Is anyone successfully doing this, or does anyone know how it can be done?

Thanks for the help!

Use comma instead of period?

Great extension!
Is it possible to get UICountingLabel to work with a comma instead of a period as a decimal point? Eg 1,3 instead of 1.3.
Have tried format = @"%,1f";

need a 'stop' method

你好能不能暴露一个 stop 的方法,计数到一半想要停止,然后立刻改成其他的值

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.

License

Hi, I really appreciate that you have this as open source, What is the License on this?

Leading zeros

Would be nice to be able to specify a fixed number of characters so it would automatically pad with leading zeros.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.