我试图保持定时器运行,即使我切换视图控制器。我尝试过单例架构,但我不太懂。推送一个新的视图控制器似乎更容易一些,但是当我调用下面的方法时,被推送的视图控制器是空白的(看起来不像我在Storyboards中创建的视图控制器)。我尝试推送的计时器视图控制器也是第二个视图控制器,如果那会改变什么的话
@objc func timerPressed() {
let timerVC = TimerViewController()
navigationController?.pushViewController(timerVC, animated: true)
}
你需要从storyboard中加载
let vc = self.storyboard!.instantiateViewController(withIdentifier: "VCName") as! TimerViewController
self.navigationController?.pushViewController(timerVC, animated: true)
不确定你的问题是你的控制器是空白的还是计时器重置。无论如何,如果你想把时间保存在内存中,而不是在导航到其他地方时释放,我建议你这样做。
创建一个Constants
类,里面有一个共享参数
可以像这样:
class AppConstants {
static let shared = AppConstants()
var timer: Timer?
}
和做你在这里做的定时器通过共享参数访问它。
AppConstants.shared.timer ...
你的问题有不同的部分。Sh_Khan告诉你加载视图控制器的方式有什么问题(简单地调用视图控制器的init方法不会加载它的视图层次结构)。通常你会在一个故事板中定义你的视图控制器的视图,所以你需要从那个故事板中实例化它。
这并没有回答如何管理计时器的问题。如果你希望你的计时器是全局的,而不是绑定到一个特定的视图控制器,单例是一个很好的方法。
贴出你用来创建单例的代码,我们可以帮助你。
编辑:更新给TimeManager一个委托:
这个想法很简单。像这样:
protocol TimeManagerDelegate {
func timerDidFire()
}
class TimerManager {
static let sharedTimerManager = TimerManager()
weak var delegate: TimeManagerDelegate?
//methods/vars to manage a shared timer.
func handleTimer(timer: Timer) {
//Put your housekeeping code to manage the timer here
//Now tell our delegate (if any) that the timer has updated.
//Note the "optional chaining" syntax with the `?`. That means that
//If `delegate` == nil, it doesn't do anything.
delegate?.timerDidFire() //Send a message to the delegate, if there is one.
}
}
然后在视图控制器中:
//Declare that the view controller conforms to the TimeManagerDelegate protocol
class SomeViewController: UIViewController, TimeManagerDelegate {
//This is the function that gets called on the current delegate
func timerDidFire() {
//Update my clock label (or whatever I need to do in response to a timer update.)
}
override func viewWillAppear() {
super.viewWillAppear()
//Since this view controller is appearing, make it the TimeManager's delegate.
sharedTimerManager.delegate = self
}