SWIFT:如何使用来自不同类的performSegueWithIdentifier

时间:2016-06-13 00:05:21

标签: ios swift segue

我试图让我的应用程序在2分钟不活动后自动返回主菜单。到目前为止,我有两个部分工作,但不是在一起..

如果没有触摸输入,应用程序会启动计数器:

请参阅Detecting when an app is active or inactive through touches in Swift

上的user4806509

从我的主视图控制器中我可以用代码控制我需要的segue:

func goToMenu()
{
    performSegueWithIdentifier("backToMenu", sender: self)
}

我已经在How to call performSegueWithIdentifier from xib?

上实施了Rob的回答代码

所以我创建了以下类和协议:

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

我的主viewcontroller是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)
}

在主ViewController中:

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)

1 个答案:

答案 0 :(得分:0)

我相信你的问题是因为你的委托声明为弱变量,你的委托在等待计时器完成时被处理掉,因此对可选项的引用会丢失(当你强制解包时返回nil它)。

尝试从CustomView类中删除weak关键字。

另一种解决方案是使用通知中心通知您的视图呼叫segue。

我提出的here

的内容

我希望这会有所帮助。