2016-11-11 108 views
1

在我的應用程序中,我有一個「主」ViewController。在其viewDidAppear體應用程序啓動,我檢索UserDefaults boolean的值:如果用戶沒有登錄,我提出模態另一個viewcontroller這樣:從UIViewController調用UIViewController方法深深地嵌套在模態中

self.performSegue(withIdentifier:"loginView", sender:self) 

這種模態啓動AuthViewController,包含的ViewController 「容器視圖」,AuthViewController的區域,其包括UIPageViewControllerAuthPageViewController)。

這最後一個有兩個「頁」:LoginViewControllerRegisterViewController

More than a thousand words

LoginViewController是用來登錄用戶:一旦用戶登錄我想在主ViewController調用一個函數(不管它做什麼)。

所以,總結一下,我在LoginViewController,我想打電話給ViewController的方法。

雖然試圖解決我發現了以下內容:

  • 我不能讓一個參考presentingViewController因爲LoginViewController沒有直接從視圖控制器打開。此外,AuthViewController沒有與present(_:animated:completion:)推出,但與self.performSegue正如我以前說過;
  • 實例化一個ViewControllerLoginViewController和調用方法的作品,但它不是一個好主意;
  • NSNotification工程就像一個魅力;
  • 顯然代表沒有工作,或者我在這個應用程序的比賽中錯過了他們的實現的一些東西;

你能幫我理解如何從我的LoginViewController中調用ViewController方法嗎?代碼示例非常受歡迎,但我很欣賞任何建議。

+2

委託,如果你初始化的將工作'ViewController'中的'LoginViewController',否則只是使用通知,如果你同時關閉多個函數,展開也可能工作 – Tj3n

回答

1

讓我如何在這種情況下使用委託的代碼解釋,

首先,你需要在LoginViewController創建委託這樣

protocol LoginViewControllerDelegate: class { 
    func goToContent(animated:Bool) 
} 

那麼對於這樣的

委託創建一個變量
weak var delegate: LoginViewControllerDelegate? 

現在在你ViewController你必須在你的準備prepareforsegue中指定這樣的delegate方法,因爲你正在使用賽格瑞這樣

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "yourSegueIdentifier" { 
     let nextScene = segue.destination as! LoginViewController 
     nextScene.delegate = self 
    } 
} 

和實施方法,這樣

func goToContent(animated: Bool) { 
    print("test") 
} 
這樣

你可以叫goToContentLoginViewController

+0

好的,有趣的,謝謝!與此同時,我發現另一種方式,不那麼優雅,以實現相同的結果:在prepareForSegue中,我在目標視圖控制器上設置一個屬性,並將其傳遞給自己。當我從LoginViewController需要它時,我通過父鏈的「鏈」來達到它。我不喜歡它,但它工作。 :-) –

+0

是的,你也可以這樣做,但試試這個解決方案一次 – Rajat

+1

等一下,Rajat:ViewController實際上並沒有爲LoginViewController準備一個segue,而是爲它的「granpa」AuthViewController –