[英]countdown UILabel not get decremented
我正在嘗試制作一個倒計時標簽,但它沒有減少。可以在代碼中找出任何一個錯誤
- (IBAction)start:(id)sender
{
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}
-(void) updateCountdown
{
int hours, minutes, seconds;
int secondsLeft = 30;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
因為每次定時器觸發時你都使用相同的值為秒int secondsLeft=30;
您必須在啟動Timer時設置secondsLeft的值,並在計時器上遞減它
- (IBAction)start:(id)sender{
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
secondsLeft=30;
}
-(void) updateCountdown {
int hours, minutes, seconds;
secondsLeft--;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
您可以將secondsLeft
和timer
聲明為ivars,每次調用updateCountdown
遞減secondsLeft
,並在沒有剩余秒數遞減時使timer
無效。
- (IBAction)start:(id)sender
{
secondsLeft = 30;
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}
- (void) updateCountdown
{
int hours, minutes, seconds;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
secondsLeft--;
if (seconds==0)
{
[timer invalidate];
}
}
你已經分配了int secondsLeft=30;
在你的updateCountdown
方法中,這是正常的。
你應該在其他地方設置secondLeft的初始值,然后在你的方法updateCountdown
你需要遞減它的值
-(void) updateCountdown {
int hours, minutes, seconds;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
if (secondsLeft > 0) secondsLeft--;
}
我發現了問題......
-(IBAction)start:(id)sender{
countDownView.hidden=NO;
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateElapsedTime) userInfo:nil repeats:YES];
secondsLeft=30;
}
-(void) updateCountdown {
int hours, minutes, seconds;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.