gpt4 book ai didi

Objective-C : NSTimer and countdown

转载 作者:太空狗 更新时间:2023-10-30 03:56:35 24 4
gpt4 key购买 nike

我知道我应该了解 Apple 的 NSTimer 文档,但我没有!我也阅读了很多关于它的问题,但找不到适合我的问题。那么这里是:

用户通过文本字段输入小时和分钟。我将它们转换为整数并将它们显示在“countDownLabel”中。

  1. 我怎样才能使倒数归零?
  2. 最好显示用户没有导入的秒数,但我想显示起来并不难。
  3. 如何通过按下 UIButton 来停止此过程?

我知道我问了很多...如果有人能提供帮助,我将不胜感激!

int intHourhs;
intHourhs=([textHours.text intValue]);
int intMinutes;
intMinutes=([textMinutes.text intValue]);
int *intSeconds;
intSeconds=0;

NSString *stringTotalTime=[[NSString alloc] initWithFormat:@"%.2i:%.2i:%.2i",intHourhs,intMinutes,intSeconds];
[countDownLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:45]];
countDownLabel.text=stringTotalTime;

最佳答案

首先你应该计算你的倒计时时间,以秒为单位并将它放在一个实例变量(ivar)中

NSTimeInterval totalCountdownInterval;

我认为为了保持良好的准确性(NSTimer 触发可以关闭多达 100 毫秒并且错误会加起来)你应该记录倒计时开始的日期,并将其放在另一个 ivar 中:

NSDate* startDate = [NSDate date];

然后你可以让一个计时器以固定的时间间隔(这里是 1 秒)重复调用你的类上的一个方法

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkCountdown:) userInfo:nil repeats:YES];

在该方法中,您可以根据总倒计时时间检查耗时并更新界面

-(void) checkCountdown:(NSTimer*)_timer {

NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate];

NSTimeInterval remainingTime = totalCountdownInterval - elapsedTime;

if (remainingTime <= 0.0) {
[_timer invalidate];
}

/* update the interface by converting remainingTime (which is in seconds)
to seconds, minutes, hours */

}

关于 Objective-C : NSTimer and countdown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7680877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com