为UILabel添加动态计数支持。
简单初始化一个UICountingLabel
,就像设置常规的UILabel
一样。
UICountingLabel* myLabel = [[UICountingLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[self.view addSubview:myLabel];
您也可以将其添加到XIB文件中,只需确保将类类型设置为UICountingLabel
而不是UILabel
,并在头文件中确保导入"UICountingLabel.h"
。
设置标签的格式。更新时,将填充单个int或float(根据您的格式设置而定)。
myLabel.format = @"%d";
或者,您还可以提供UICountingLabelFormatBlock
,允许对文本的格式进行更多控制。
myLabel.fomatBlock = ^(NSString *)(CGFloat progress) {
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
用于使用格式化字符串,如果指定了formatBlock
,则它将优先于format
。
可选地,设置模式。默认为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:
方法,因此您也可以在格式中包含任意文本,例如,使用@"积分: %i"
。
当前有四种计数模式。
UILabelCountingMethodLinear
从开始到结束线性计数。
UILabelCountingMethodEaseIn
缓动开始速度慢,在接近结束时加快计数速度,并在最终值处突然停止。
UILabelCountingMethodEaseOut
缓动开始速度快,在接近目的地值时减速。
UILabelCountingMethodEaseInOut
缓动/非缓动开始速度慢,在中间加速,然后接近目的地时减速。它是一个平滑且看起来很棒的曲线,是默认方法。