如何使用Swift在ViewControllers中继续执行某个功能?

时间:2016-03-04 00:02:33

标签: ios swift nstimer viewcontroller

我有一个NSTimer(),它在按钮点击时开始。如果我希望timer显示在标签上,我可以在同一个视图控制器中执行此操作,但我希望计时器继续,值(1 ... 2 ... 3)为显示在下一个视图控制器上。我有一个标签,在下一个视图控制器上显示时间变量,但它只显示按下按钮时的时间变量值,并且不会继续。传递时间变量但运行它的函数不是。我怎么能这样做?

var timer = NSTimer()

var time = 0

在viewDidLoad中:

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timerFunc"), userInfo: nil, repeats: true)

    func timerFunc() {

        time++

//time label displays the time (1..2...3 etc)

        timeLabel.text = String(time)

    }

SecondSceneViewController有一个从这个视图控制器传递的时间变量:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            var secondScene = segue.destinationViewController as!           
                              SecondViewController

            secondScene.time = time
    }

当我转到secondViewController时,时间变量内的值是按下按钮时的时间变量并且它不会继续运行。我如何将计时器传递给下一个视图控制器以显示值?

3 个答案:

答案 0 :(得分:4)

IMO你应该将定时器的代码提取到Singleton,然后从两个ViewControllers中访问它

这是一个让你入门的简单方法:

Devices

}

答案 1 :(得分:3)

我会创建一个处理计时器事件的单例。

    let myTimerNotificationNameKey = "timerKey"
    let myTimerNotificationUserInfoTimeKey = "timerUserInfoKey"

    class myTimer {
      static let sharedInstance = myTimer()
      var timer: NSTimer
      var time = 0

      func startTimer() {
         time = 0
         timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerFunc:", userInfo: nil, repeats: true)

      }

      func stopTimer() {
        timer.invalidate()
        timer = nil
      }

      func timerFunc(timer: NSTimer) {
            NSNotificationCenter.defaultCenter().postNotificationName(myTimerNotificationNameKey,object: nil, userInfo: {myTimerNotificationUserInfoTimeKey: time++})

      }
    }

在第一个视图控制器上,调用将启动计时器的myTimer.sharedInstance.startTimer()函数。但首先要记得听通知。通知将收到带有时间计数的用户信息字典。在第二个视图控制器上执行相同的操作。

现在您有一个可以跨多个视图控制器监听的计数。一旦停止需要,请记得停止计时器。

注意:我还没有编译这段代码。

答案 2 :(得分:0)

如果保留这两个变量

var timer = NSTimer()
var time = 0

在课外,它们变为全局,你可以从另一个视图控制器访问它们。

就像这个例子:

import UIKit
import CoreData

var fromJSON = true

// Retreive the managedObjectContext from AppDelegate
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

class CoreDataController: UIViewController {

另一种选择是与通知中心合作:

NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "batteryLevelChanged:",
    name: UIDeviceBatteryLevelDidChangeNotification,
    object: nil)

@objc func batteryLevelChanged(notification: NSNotification){     
    //do stuff
}