-
背景
实现类似于支付宝余额宝金额的数字自增动画,查找了一些轮子,稍微看了两个,一个swift实现,但是是swift1.几,有一些错误,本身对swift不熟,放弃。另一个倒是没有错,但是是label的分类,引入后跟系统已有的label分类有冲突,放弃。不用库了,自己实现。恰好阅读到缓冲函数的三次贝塞尔曲线,和自定义函数曲线。发现用一个数学函数就可以模拟曲线运动。
- 效果
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
网友评论