如何使用特定数量的计数在 SWIFT 中循环 NSTimer [英] How to loop NSTimer in SWIFT with a specific number of counting

查看:60
本文介绍了如何使用特定数量的计数在 SWIFT 中循环 NSTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用特定数量的计数来循环计时器...例如... 1, 2, 3, 4, 5

I am trying to loop a timer with a specific number of counting... eg... 1, 2, 3, 4, 5

然后再次循环,同样的计数,10次,然后停止.

then loop again, the same counting, 10 times, then stop.

我能够进行计数,但无法进行循环计数.

I was able to do the counting, but I can't do the looping of the counting.

我做错了什么?

var times = 0
var stopCounting = 10

@IBAction func buttonPressed(sender: UIButton) {
   self.startTimer()
}

func startTimer(){
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("startCounting"), userInfo: nil, repeats: true)
    }

func startCounting (){

times += 1
if times < stopCounting + 1{

        if counter > -1 && counter < 6 {
            counting.text = String(counter++)
        } else if counter == Int(counting.text) {
            counting.text = "0"
        }

    }

推荐答案

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var strTime: UILabel!

    var timer = NSTimer()
    var endTime: NSTimeInterval = 0
    var now: NSTimeInterval { return NSDate().timeIntervalSinceReferenceDate }
    var times = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func updateText(){
        let time = Int(ceil(endTime - now))

        if time == 0 {
            times++
            if times == 10 {
                strTime.text = "end"
                timer.invalidate()
            }
            endTime = NSDate().timeIntervalSinceReferenceDate + 5
        } else {
            strTime.text = time.description
        }
    }

    @IBAction func buttonPressed(sender: UIButton) {
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateText", userInfo: nil, repeats: true)
        endTime = NSDate().timeIntervalSinceReferenceDate + 5
        sender.hidden = true
    }
}

要使其从 1 计数到 5,您需要从 ceil 更改为 floor,abs() 并添加 +1

to make it count from 1 to 5 you need to change from ceil to floor, abs() and add +1

func updateText(){
    let time = Int(floor(abs(endTime - now - 5)))
    if time == 5 {
        times++
        if times == 10 {
            strTime.text = "10" + "     " + "0"
            timer.invalidate()
        }
        endTime = NSDate().timeIntervalSinceReferenceDate + 5
    } else {
        strTime.text = times.description + "     " + (time+1).description
    }
}

这篇关于如何使用特定数量的计数在 SWIFT 中循环 NSTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆