【问题标题】:SWIFT: how to use performSegueWithIdentifier from different classSWIFT:如何使用不同类的 performSegueWithIdentifier
【发布时间】: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,我在原帖中添加了工作代码。

标签: ios swift segue


【解决方案1】:

我相信你的问题是因为你的委托被声明为一个弱变量,你的委托在你等待计时器完成时被释放,因此对可选的引用丢失了(当你强制展开时返回 nil它)。

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

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

类似于我提出的here

我希望这会有所帮助。

【讨论】:

  • 谢谢你的反应,我试过去掉weak,还是不行,但是我实现了NSNotificationCenter的方案,效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 2014-11-15
相关资源
最近更新 更多