【问题标题】:CountDown using NSTimer in swift在 swift 中使用 NSTimer 倒计时
【发布时间】:2016-05-01 22:39:10
【问题描述】:

我仍在学习 swift,我正在尝试设计一个应用程序,在一个部分中,我将这个游戏计时器设置为 7 分钟(稍后将添加弄清楚如何让客户端更改它),因为现在是 7:00,我添加了 2 个按钮, 开始,暂停。我想让开始,开始倒计时直到 00:00,然后我打算添加一个弹出消息说时间到了!。

到目前为止的代码:

import UIKit

class ViewController: UIViewController {
@IBOutlet var countDown: UILabel!

var counter = 60
var timer = NSTimer()

func update() {

    if counter > 0 {
        countDown.text = String(counter--)
    }

}

@IBAction func start(sender: UIButton) {

    timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)

}

@IBAction func pause(sender: UIButton) {
     // timer.invalidate() stops the whole thing...
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

但是,应用程序不断崩溃...我不知道如何使计时器超过 60 秒,例如如何表示它。

【问题讨论】:

  • 能否说明应用崩溃时出现的错误?
  • 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[IwannaPlay.ViewController Start:]:无法识别的选择器发送到实例 0x7fd039c25820'
  • 去检查界面生成器上的开始按钮。似乎它与错误的视图控制器和方法有关 ->(IwannaPlay.ViewController Start:])
  • @bpolat 原来我的按钮链接到 3 个东西,你刚刚解决了我的大部分问题。

标签: swift nstimer countdown


【解决方案1】:

这不是我做倒计时的方式。

@IBAction func start(sender: UIButton) {
     self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil, repeats: true)
     NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
    startTime = NSDate() // new instance variable that you would need to add.
}

func update() {
    let elapsedTime = NSDate().timeIntervalSinceDate(startTime)
    let currTime = totalTime - elapsedTime 
    //total time is an instance variable that is the total amount of time in seconds that you want
    countDown.text = String(currTime)
    if currTime < 0 {
        timer.invalidate()
        //do other stuff that you need to do when time runs out.
    }
}

还要确保您的 IBAction 插座在界面生成器中是正确的。

【讨论】:

  • 好的,所以将它添加到我的全局变量中,var totalTime = 60 var timer = NSTimer() var startTime = NSDate() 并在 Start 函数中添加: startTime = NSDate() 这是我的更新函数: let elapsedTime = NSDate().timeIntervalSinceDate(startTime) let currTime = totalTime - Int(elapsedTime) countDown.text = String(currTime) if currTime
  • 但是应用程序仍然崩溃,这是我收到的消息:由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[IwannaPlay.ViewController Start:]: unrecognized selector sent to instance 0x7fd039c25820”
  • @AymanAbuassonon 好的,这意味着您使用的选择器有问题。检查我在启动函数上更新的代码,尤其是#selector(ViewController.update(_:)) 行。但是错误也可能在您的界面构建器文件中。尝试确保 IBAction 正确。
  • 修复了崩溃的东西后,它现在可以完美运行了,这对我来说是全新的,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多