繁体   English   中英

在SWIFT中制作合法的倒数计时器

[英]Making a Legit Countdown Timer in SWIFT

我试图在按下按钮时让标签倒数,以(hr,min,sec)的方式显示倒数。 我有点尝试连接我发现的两个不同的代码。 这是我所拥有的:

*updated code (some psuedo code)*

var timer = NSTimer()

func timerResults() {
    let theDate = NSDate()
    var endTime = theDate //+ 6 hours
    let timeLeft = endTime - theDate
    timeLeftLabel.text = "\(timeLeft)"
}


@IBOutlet weak var timeLeftLabel: UILabel!

@IBAction func IBbtnUpdateTap(sender: UIButton){

        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerResults"), userInfo: nil, repeats: true)

    }

另外,即使应用未运行,我如何积极进行倒计时? 本质上,如果用户在6小时内回来,我将创建一个奖励系统。

我现在不能给出很长的答案,但是最简单的方法如下:

当用户以一定的秒数启动计时器时,计算计时器应该终止的确切日期( end time = now + amount of seconds )。 现在,您可以使用计算出的剩余time left = end time - now (剩余time left = end time - now )在每次显示刷新时更新标签。

这样,可以保证重新启动应用程序的时间(当然,您需要使用NSUserDefaults或其他方式保存结束日期),并且还可以确保计时器速度没有波动( NSTimer不能保证)

您缺少或需要更正的项目如下:

var startTime: NSDate = NSDate()
var endTime: NSDate?

func viewDidLoad() {
    let clock = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countdown", userInfo: nil, repeats: true)
    endTime = startTime.dateByAddingTimeInterval(21600)
}

func countdown() {
    printSecondsToHoursMinutesSeconds(Int(timeLeft()))
}

func timeLeft() -> Double {
    return endTime!.timeIntervalSinceNow
}

要测量应用程序未运行时的时间,需要保存应用程序进入后台的时间,然后比较再次打开应用程序时所保存的时间。 时间可以另存为NSDate 比较两个NSDates可以NSTimeInterval ,即两个日期之间经过的秒数。 例如:

let remainingTime = savedTime.timeIntervalSinceNow

请参阅您的应用程序委托中的applicationDidBecomeActive:applicationDidEnterBackground:以获取比较日期并将其保存到NSUserDefaults中的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM