[英]In Objective-C How Do I Increase a Number Displayed by UILabel Gradually?
假设我想将UILabel显示的数字从0%增加
UILabel *percentage.text = [NSString stringWithFormat:@" %ld%%", 0];
2秒内达到50%
percentage.text = [NSString stringWithFormat:@" %ld%%", 0]
这是我尝试使用NSTimer的方法:
self.percent = 0;
self.timer = [NSTimer timerWithTimeInterval:0.04
target:self
selector:@selector(updateLabel)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
//updateLabel
- (void)updateLabel{
self.percentage.text = [NSString stringWithFormat:@" %ld%%", self.percent++];
if (self.percent > 50) {
[self.timer invalidate];
self.timer = nil;
}
}
但是UI看起来非常生涩,一点也不平滑,就像所有更改都堆叠在一起一样,有时会应用,但不确定何时应用,并且花费的时间肯定超过2秒。 这是因为0.04秒太短了吗?
有更好的方法吗?
我不知道这是否是您的问题的原因...
不要每次都将新时间附加到标签文本中; 每次计时器触发时,将标签设置为新值:
self.percentage.text = [NSString stringWithFormat: @"%ld%%",
self.percent++]
调整计时器中的时间间隔,即可顺利执行:
self.timer = [NSTimer timerWithTimeInterval:0.0001
target:self
selector:@selector(updateLabel)
userInfo:nil
repeats:YES];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.