在NStimer倒计时延迟1-2秒

时间:2016-05-03 22:24:39

标签: swift2 nstimer countdown stopwatch

在swift 2中在线查​​看countDown实现后,我无法找到以倒计时方式工作的任何人。所以我做了我自己但是当它达到第二个01时需要2秒才能变成59.例如,如果计时器在05:01,它需要2秒的滞后或计时器冻结,那么它变成4:59。 它看起来很奇怪,我是一个完整的初学者,所以我的代码是一场灾难,现在是:

{foreach from=$items item="product"}
    {if $product}
        {assign var="obj_id" value="`$block.block_id`000`$product.product_id`"}
        {include file="common/image.tpl" image_width=$block.properties.thumbnail_width image_height=$block.properties.thumbnail_height obj_id=$obj_id images=$product.main_pair href="products.view?product_id=`$product.product_id`"|fn_url}
    {/if}
{/foreach}

1 个答案:

答案 0 :(得分:1)

因为您忘记更新标签:

if (currentSeconds > 9)   {
    countDown.text = "0\(currentMins):\(currentSeconds)"
    currentSeconds -= 1
} else if ( currentSeconds > 0) && (currentSeconds <= 9) {
    countDown.text = "0\(currentMins):0\(currentSeconds)"
    currentSeconds -= 1
} else {
    countDown.text = "0\(currentMins):00" // <-- missed this
    currentMins -= 1
    currentSeconds = 59
}

但是,如果您使用NSDateFormatter格式化剩余秒数而不是管理2个单独的变量,情况会更好:

class ViewController: UIViewController, UITextFieldDelegate {
    var secondsLeft: NSTimeInterval = 359
    var formatter = NSDateFormatter()

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)

        formatter.dateFormat = "mm:ss"
        formatter.timeZone = NSTimeZone(abbreviation: "UTC")!
    }

    func updateTime()
    {
        countDown.text = formatter.stringFromDate(NSDate(timeIntervalSince1970: secondsLeft))
        secondsLeft -= 1

        if secondsLeft == 0 {
            countDown.text = "time is up!"
            timer.invalidate()
        }
    }
}