我创建一个从10到0的倒数计时器。我创建一个uilabel,以秒为单位显示计数器。现在我希望标签显示计数器分钟和秒,如:00:00。 我怎样才能做到这一点? 这是我的倒计时代码:
-(void)countdown
{
countdownCounter -= 1;
countdown.text = [NSString stringWithFormat:@"%i", countdownCounter];
}
-(IBAction)strat:(id)sender
{
countdownCounter = 10;
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countdown) userInfo:nil repeats:YES];
}
}
谢谢!
答案 0 :(得分:3)
这可以使用一次和一个标签来完成。请尝试使用以下代码:
int seconds = [countDown.text intValue] % 60;
int minutes = ([countDown.text intValue] / 60) % 60;
countDown.text = [NSString stringWithFormat:@"%2d:%02d", minutes, seconds];
答案 1 :(得分:2)
以完全相同的方式完成,只需添加另一个计时器。
countdownTimer2 = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(countdown2) userInfo:nil repeats:YES];
-(void)countdown2
{
countdownCounterMinutes -= 1;
}
and change countdown to
-(void)countdown
{
countdownCounter -= 1;
countdown.text = [NSString stringWithFormat:@"%i%i", countdownCounterMinutes, countdownCounter];
}
答案 2 :(得分:1)
对于那些最终得到答案的人我是这样做的:
-(IBAction)start
{
timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}
-(void)updateTimer:(NSTimer *)timer {
currentTime -= 10 ;
[self populateLabelwithTime:currentTime];
if(currentTime <=0)
[timer invalidate];
}
- (void)populateLabelwithTime:(int)milliseconds {
seconds = milliseconds/1000;
minutes = seconds / 60;
hours = minutes / 60;
seconds -= minutes * 60;
minutes -= hours * 60;
NSString * result1 = [NSString stringWithFormat:@"%@%02d:%02d:%02d:%02d", (milliseconds<0?@"-":@""), hours, minutes, seconds,milliseconds%1000];
result.text = result1;
}
在viewDidLoad中我为倒计时时间设置currentTime,以毫秒为单位。 希望你明白......
答案 3 :(得分:0)
我用分钟和秒来格式化数字(来自浮点数) 这样,谢谢你的回答。 (希望这有助于另一个)
- (void)ticTimer
{
self.current -= self.updateSpeed;
CGFloat progress = self.current / self.max;
[self populateLabelwithTimeFormatted:self.current];
/// TimeLabelNode.text = [NSString stringWithFormat:@"%f", progress];
// * Time is over
if (self.current <= self.min) {
[self stop];
_TimeLabelNode.text= @"time up!";
}
}
- (void)populateLabelwithTimeFormatted:(float)time {
//convert float into mins and seconds format
int mytime = (int) _current;
int seconds = mytime%60;
int minutes = mytime / 60 % 60;
NSString * result1 = [NSString stringWithFormat:@"%2d:%02d", minutes, seconds];
_TimeLabelNode.text = result1;
}