繁体   English   中英

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

[英]SWIFT: how to use performSegueWithIdentifier from different class

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

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

请参阅user4806509关于通过Swift中的触摸检测应用是处于活动状态还是非活动状态的答案

从我的主viewcontroller中,我可以使用代码控制我需要的segue:

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

我已经实现了Rob关于如何从xib调用performSegueWithIdentifier的答案中的代码

因此,我创建了以下类和协议:

protocol CustomViewDelegate: class {
    func goToMenu()
}
class CustomView: UIView
{
weak var delegate: CustomViewDelegate?
    func go() {
        delegate?.goToMenu()
    }
}

计时器用尽时,函数go()被成功调用。 但是委托?.goToMenu()不起作用。 如果我将其更改为:委托!.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)

我相信您的问题是,因为您的委托被声明为弱变量,所以在等待计时器完成时您的委托正在被处决,因此对可选参数的引用会丢失(当您强制拆开它时返回nil)。

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

另一个解决方案是使用通知中心来通知您的视图以请求segue。

在这里提出的建议

我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM