【发布时间】:2016-06-13 00:05:21
【问题描述】:
我正在尝试让我的应用在 2 分钟不活动后自动返回主菜单。到目前为止,我的两个部分都在工作,但没有一起工作..
如果没有触摸输入,应用程序会启动一个计数器:
在Detecting when an app is active or inactive through touches in Swift上查看user4806509的回答
从我的主视图控制器中,我可以使用代码控制我需要的转场:
func goToMenu()
{
performSegueWithIdentifier("backToMenu", sender: self)
}
我已经实现了 Rob 在How to call performSegueWithIdentifier from xib? 上的回答中的代码
所以我创建了以下类和协议:
protocol CustomViewDelegate: class {
func goToMenu()
}
class CustomView: UIView
{
weak var delegate: CustomViewDelegate?
func go() {
delegate?.goToMenu()
}
}
当计时器用完时,函数 go() 被(成功)调用。但是委托?.goToMenu() 不起作用。如果我将其更改为:delegate!.goToMenu(),应用程序崩溃:
fatal error: unexpectedly found nil while unwrapping an Optional value
我的主视图控制器是一个 CustomViewDelegate 并且 viewDidLoad 包含:
let myCustomView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0] as! CustomView
myCustomView.delegate = self
我有正确的 xib 文件,并且该部分正在工作。
我似乎找不到这个看似简单的问题的解决方案,有人有解决办法吗?或者更好的是,对我的问题有更优雅的解决方案?
谢谢!
编辑:解决方案:
我已经删除了所有旧代码并实现了 NSNotification 方法:
在 UIApplication 中:
let CallForUnwindSegue = "nl.timfi.unwind"
func delayedAction()
{
NSNotificationCenter.defaultCenter().postNotificationName(CallForUnwindSegue, object: nil)
}
在主视图控制器中:
let CallForUnwindSegue = "nl.timfi.unwind"
func goToMenu(notification: NSNotification)
{
performSegueWithIdentifier("backToMenu", sender: self)
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
在viewDidLoad中:NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PeriodViewController.goToMenu), name:CallForUnwindSegue , object: nil)
【问题讨论】:
-
要返回故事板中的上一个场景,您需要使用
unwind segue使用prepareForUnwind:方法。这是你在做什么?示例:spin.atomicobject.com/2014/10/25/ios-unwind-segues -
你应该使用通知中心,从我的角度来看,这将是一个更优雅、更干净的解决方案。 @Daniel_Ormeño 链接了详细的答案。
-
感谢您的 cmets,我在原帖中添加了工作代码。