使用 NSTimer 从 0.00 计数到 176.20
count up from 0.00 to 176.20 with NSTimer
我正在开发一个应用程序,我想为我的应用程序中的数字设置动画。我知道我需要使用 NSTimer。只是不确定如何。例如,我希望应用程序从 0.00 计数到 176.20 (self.total.text)。
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES];
- (void)update{
float currentTime = [self.total.text floatValue];
float newTime = currentTime + 0.1;
self.total.text = [NSString stringWithFormat:@"%f", newTime];
}
您需要决定您要计算的增量。您希望在 176.20 处止损,因此看起来 0.1 秒的增量就是您想要的。您需要一个变量来存储当前位置。
Obj-c///
const float limit = 176.2f
@property (nonatomic) float seconds;
@property (nonatomic, strong) NSTimer *updateTimer;
// Initialize
self.seconds = 0.0f;
self.updateTimer = [NStimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(timerFired) userInfo:nil repeats:true];
Swift///
var seconds = 0.0
let limit = 176.2
let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("timerFired"), userInfo: nil, repeats: true)
然后您需要创建一个用于在每次计时器触发时更新标签的函数和一个调度计时器的函数。
Obj-c///
- (void)timerFired {
self.seconds += 0.1f;
self.label.text = [NSString stringWithFormat:@"%f", self.seconds];
if (self.seconds >= limit) {
[self.updateTimer invalidate];
}
}
Swift///
func timerFired() {
seconds += 0.1 //Increment the seconds
label.text = "\(seconds)" //Set the label
if (seconds >= limit) {
timer.invalidate()
}
}
我正在开发一个应用程序,我想为我的应用程序中的数字设置动画。我知道我需要使用 NSTimer。只是不确定如何。例如,我希望应用程序从 0.00 计数到 176.20 (self.total.text)。
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES];
- (void)update{
float currentTime = [self.total.text floatValue];
float newTime = currentTime + 0.1;
self.total.text = [NSString stringWithFormat:@"%f", newTime];
}
您需要决定您要计算的增量。您希望在 176.20 处止损,因此看起来 0.1 秒的增量就是您想要的。您需要一个变量来存储当前位置。
Obj-c///
const float limit = 176.2f
@property (nonatomic) float seconds;
@property (nonatomic, strong) NSTimer *updateTimer;
// Initialize
self.seconds = 0.0f;
self.updateTimer = [NStimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(timerFired) userInfo:nil repeats:true];
Swift///
var seconds = 0.0
let limit = 176.2
let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("timerFired"), userInfo: nil, repeats: true)
然后您需要创建一个用于在每次计时器触发时更新标签的函数和一个调度计时器的函数。
Obj-c///
- (void)timerFired {
self.seconds += 0.1f;
self.label.text = [NSString stringWithFormat:@"%f", self.seconds];
if (self.seconds >= limit) {
[self.updateTimer invalidate];
}
}
Swift///
func timerFired() {
seconds += 0.1 //Increment the seconds
label.text = "\(seconds)" //Set the label
if (seconds >= limit) {
timer.invalidate()
}
}