最近在項(xiàng)目中有個(gè)需求是要將金額數(shù)字以滾動(dòng)增加的方式展示出來.效果類似于支付寶余額的顯示樣子
代碼如下:
//創(chuàng)建
- (void)viewDidLoad {
[super viewDidLoad];
self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 300, 80)];
self.moneyLabel.backgroundColor = [UIColor cyanColor];
self.moneyLabel.textColor = [UIColor redColor];
self.moneyLabel.textAlignment = NSTextAlignmentRight;
self.moneyLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:50];
self.moneyLabel.text = @"0.00";
[self.view addSubview:self.moneyLabel];
}
//點(diǎn)擊修改數(shù)字
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self setNumberTextOfLabel:self.moneyLabel WithAnimationForValueContent:1000000000.00];
}
//具體實(shí)現(xiàn)
//實(shí)現(xiàn)方法
- (void)setNumberTextOfLabel:(UILabel *)label WithAnimationForValueContent:(CGFloat)value
{
CGFloat lastValue = [label.text floatValue];
CGFloat delta = value - lastValue;
if (delta == 0) return;
if (delta > 0) {
CGFloat ratio = value / 60.0;
NSDictionary *userInfo = @{@"label" : label,
@"value" : @(value),
@"ratio" : @(ratio)
};
[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(setupLabel:) userInfo:userInfo repeats:YES];
}
}
- (void)setupLabel:(NSTimer *)timer
{
NSDictionary *userInfo = timer.userInfo;
UILabel *label = userInfo[@"label"];
CGFloat value = [userInfo[@"value"] floatValue];
CGFloat ratio = [userInfo[@"ratio"] floatValue];
static int flag = 1;
CGFloat lastValue = [label.text floatValue];
CGFloat randomDelta = (arc4random_uniform(2) + 1) * ratio;
CGFloat resValue = lastValue + randomDelta;
if ((resValue >= value) || (flag == 50)) {
label.text = [NSString stringWithFormat:@"%.2f", value];
flag = 1;
[timer invalidate];
timer = nil;
return;
} else {
label.text = [NSString stringWithFormat:@"%.2f", resValue];
}
flag++;
}
實(shí)現(xiàn)效果如下