利用二次函数和NSTimer 实现简单数字自增动画

2016-04-02  本文已影响118人  天泽圣司tzss
Untitled.gif
#import "ViewController.h"
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *label;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger index;

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.label.textColor = [UIColor redColor];
    
    NSTimeInterval duration = 5;
    NSMutableArray *numberArray = [NSMutableArray array];
    for (NSInteger i = 0; i <= duration * 60; i++) {
        float time = 1 / (duration * 60) * i;
        time = quadraticEaseInOut(time);
        float value = interpolate(0, 100, time);
        [numberArray addObject:@((NSInteger)value).stringValue];
    }
    self.index = 0;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(tick:) userInfo:numberArray repeats:YES];
    [self.timer setFireDate:[NSDate distantPast]];
    
}

- (void)tick:(NSTimer *)timer {
    if (self.index <= 60 * 5) {
        self.label.text = timer.userInfo[self.index];
        self.index++;
    } else {
        [timer setFireDate:[NSDate distantFuture]];
    }
}

float interpolate(float from, float to, float time)
{
    return (to - from) * time + from;
}

float quadraticEaseInOut(float t)
{
    return (t < 0.5)? (2 * t * t): (-2 * t * t) + (4 * t) - 1;
}

- (void)dealloc {
    self.timer = nil;
}

@end
上一篇 下一篇

猜你喜欢

热点阅读