swift - 如何使用特定数量的计数在 SWIFT 中循环 NSTimer

标签 swift nstimer

我正在尝试循环一个具有特定计数次数的计时器... 例如... 1, 2, 3, 4, 5

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

我可以进行计数,但无法进行循环计数。

我做错了什么?

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

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 - 如何使用特定数量的计数在 SWIFT 中循环 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873055/

相关文章:

swift - Swift 中的@selector()?

xcode - 使用 HH :MM:SS? 的 NSTimer

swift - 如何使用自委托(delegate)在 TypeScript 中实现 NativeScript 类?

ios - 如何使 UIToolbarItem 拉伸(stretch)到全宽?

ios - 如何调整自定义tableView Cell中的标签高度和宽度

ios - NSTimer 不调用方法

ios - NSTimer 和 NSDateFormatter 麻烦。我的 timerLabel 刷新后消失了吗?

ios - 是什么导致 NSTimer 运行代码的速度比预期的要慢

ios快速更改结果数组的类型

ios - 如何修复 SplitViewController 中的底部灰色条?