簡體   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