Ios 如何添加重置功能?

Ios 如何添加重置功能?,ios,xcode,swift,Ios,Xcode,Swift,如何向IBOutlet添加重置功能,当前单击按钮时计时器将启动,再次单击同一按钮时计时器将停止,但第三次单击时将再次启动,但我希望重置 @IBAction func start(sender: AnyObject) { if !timer.valid{ let aSelector : Selector = "updateTime" timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, s

如何向IBOutlet添加重置功能,当前单击按钮时计时器将启动,再次单击同一按钮时计时器将停止,但第三次单击时将再次启动,但我希望重置

 @IBAction func start(sender: AnyObject) {
     if !timer.valid{

    let aSelector : Selector = "updateTime"
    timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
    startTime = NSDate.timeIntervalSinceReferenceDate()
        stoptimer.text = String(arc4random_uniform(4)+1)
     }
     else{
        timer.invalidate()


        }



}

为什么不在全局变量中保存一个按钮状态,这样您就可以随心所欲了

下面是一个简单的例子:(你也可以在这里找到按钮的标题)


您可以为其设置一个bool,如下代码所示:

var stopTime = false

@IBAction func start(sender: AnyObject) {

    if !timer.valid && !stopTime{

        let aSelector : Selector = "updateTime"
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: aSelector, userInfo: nil, repeats: true)
        var startTime = NSDate.timeIntervalSinceReferenceDate()
        stoptimer.text = String(arc4random_uniform(4)+1)

    }else if stopTime{

        //reset you timer here
        //reset your bool as per your need.
        println("Reset")

    } else {

        stopTime = true
        timer.invalidate()
    }
}
当您在计时器运行时单击开始按钮时,它将进入else并将您的
stopTime
bool设置为
true
,以便下次按开始按钮时,它不会进入该if条件,因为此时
stopTime
true

或不带布尔值

在类中,将计时器声明为可选

var timer: NSTimer?
在@iAction函数中:

if timer != nil {
    timer?.invalidate()
    timer = nil
} else {
    timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
    // Do everything you want with your timers
}

当然,这也是可能的。它应该给用户一个解决方法。你确定它会重置它,因为它看起来只是停止计时器,我希望计时器停止,然后下一次单击它将重置。
if timer != nil {
    timer?.invalidate()
    timer = nil
} else {
    timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
    // Do everything you want with your timers
}