如何使用NSTimer进行倒计时?

Gio*_*odz 20 xcode nstimer swift

如何NSTimer使用Swift 进行倒计时?

Big*_*man 39

问题1:

@IBOutlet var countDownLabel: UILabel!

var count = 10

override func viewDidLoad() {
    super.viewDidLoad()

    var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
}

func update() {
    if(count > 0) {
        countDownLabel.text = String(count--)
    }
}
Run Code Online (Sandbox Code Playgroud)

问题2:

你可以做到这两点.SpriteKit是用于场景,动画等的SDK.简单视图应用程序是项目模板.他们不应该发生冲突

  • 考虑使用 count-=1 而不是 C 语言中的 -- 运算符。我将 String(count) 放在下面,count-=1。 (2认同)

Mic*_*man 33

带闭包的 Swift 5:

class ViewController: UIViewController {
    
var secondsRemaining = 30
    
@IBAction func startTimer(_ sender: UIButton) {
        
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
        if self.secondsRemaining > 0 {
            print ("\(self.secondsRemaining) seconds")
            self.secondsRemaining -= 1
        } else {
            Timer.invalidate()
        }
    }
            
}
Run Code Online (Sandbox Code Playgroud)

  • 从我在这里可以看到,这将导致保留周期(我大约 95% 确定 - 没有进行测试)。您需要弱捕获 self 才能从计时器闭包中引用它。您还使用大写 T 来命名名称“Timer”,使其看起来像一个类型,因此“Timer.invalidate()”读取为静态函数。这应该像“{[weak self](timer) in”那样进行更改,以捕获weak self并明确“timer”是计时器的实例。 (3认同)

Gur*_*ngh 25

Swift 4.1 和 Swift 5. updatetime 方法将在每秒调用一次,并且秒将显示在 UIlabel 上。

     var timer: Timer?
     var totalTime = 60
    
     private func startOtpTimer() {
            self.totalTime = 60
            self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        }
    
    @objc func updateTimer() {
            print(self.totalTime)
            self.lblTimer.text = self.timeFormatted(self.totalTime) // will show timer
            if totalTime != 0 {
                totalTime -= 1  // decrease counter timer
            } else {
                if let timer = self.timer { 
                    timer.invalidate()
                    self.timer = nil
                }
            }
        }
    func timeFormatted(_ totalSeconds: Int) -> String {
        let seconds: Int = totalSeconds % 60
        let minutes: Int = (totalSeconds / 60) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
Run Code Online (Sandbox Code Playgroud)


小智 24

在Swift 3.0中,这将起作用:

var counter = 30

override func viewDidLoad() {
    super.viewDidLoad()

    Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}



@objc func updateCounter() {
    //example functionality
    if counter > 0 {
        print("\(counter) seconds to the end of the world")
        counter -= 1
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 伟大的!为我工作:)我刚刚添加了计时器失效以避免多次调用计时器时出现问题。 (2认同)

Hen*_*Lee 7

定时器的变量

var timer = 60
Run Code Online (Sandbox Code Playgroud)

NSTimer以1.0为间隔

var clock = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "countdown", userInfo: nil, repeats: true)
Run Code Online (Sandbox Code Playgroud)

在这里你可以减少计时器

func countdown() {
    timer--
}
Run Code Online (Sandbox Code Playgroud)


nul*_*are 6

供新手在 Playground 中使用,在 Swift 5、Xcode 11 中:

Import UIKit

var secondsRemaining = 10
    
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
    if secondsRemaining > 0 {
        print ("\(secondsRemaining) seconds")
        secondsRemaining -= 1
    } else {
        Timer.invalidate()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗨@shader,NSTimer 类现在更改为 Timer,也许我应该澄清一下 (2认同)

小智 6

对于鸡蛋倒计时器。

class ViewController: UIViewController {
    var secondsRemaining = 60
    var eggCountdown = 0
    let eggTimes = ["Soft": 5, "Medium": 7,"Hard": 12]
    
    
    
    @IBAction func hardnessSelected(_ sender: UIButton) {
        let hardness = sender.currentTitle!
        let result = eggTimes[hardness]!
        eggCountdown = result * secondsRemaining
        
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
                if self.eggCountdown > 0 {
                    print ("\(self.eggCountdown) seconds.")
                    self.eggCountdown -= 1
                } else {
                    Timer.invalidate()
                }
            }
        
    }
    
}
Run Code Online (Sandbox Code Playgroud)

  • 跟安吉拉学的?? (3认同)

Gia*_*ang 5

雨燕3

private let NUMBER_COUNT_DOWN   = 3

var countDownLabel = UILabel()
var countDown = NUMBER_COUNT_DOWN
var timer:Timer?


private func countDown(time: Double)
{
    countDownLabel.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    countDownLabel.font = UIFont.systemFont(ofSize: 300)
    countDownLabel.textColor = .black
    countDownLabel.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)

    countDownLabel.textAlignment = .center
    self.view.addSubview(countDownLabel)
    view.bringSubview(toFront: countDownLabel)

    timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true)
}

func updateCountDown() {
    if(countDown > 0) {
        countDownLabel.text = String(countDown)
        countDown = countDown - 1
    } else {
        removeCountDownLable()
    }
}

private func removeCountDownLable() {
    countDown = NUMBER_COUNT_DOWN
    countDownLabel.text = ""
    countDownLabel.removeFromSuperview()

    timer?.invalidate()
    timer = nil
}
Run Code Online (Sandbox Code Playgroud)