2017-09-20 147 views
0

我試圖以模態方式呈現視圖控制器,並獲得着名的Presenting view controllers on detached view controllers is discouraged錯誤。我研究了它,並且共識解決方案似乎是從父母那裏做出的演示文稿,我嘗試過但沒有成功。我懷疑問題是因爲導航控制器是作爲一個靜態屬性從結構實例化的(爲了讓其他視圖控制器更容易彈出到根,因爲這是UX所要求的)。如何從獨立視圖控制器呈現視圖控制器?

struct SectionNavigationControllers { 
    static var one = SectionNavigationController() 
    static var two = SectionNavigationController() 
    static var three = SectionNavigationController() 
    static var four = SectionNavigationController() 
} 

這裏是其中所述導航控制器中的一個被創建(使用本結構):

let SectionOneRoot = MasterSearchViewController() 

func addNavigationController() { 

    self.addChildViewController(SectionOneRoot) 
    SectionOneRoot.didMove(toParentViewController: self) 
    SectionNavigationControllers.one = SectionNavigationController(rootViewController: SectionOneRoot) 
    view.addSubview(SectionNavigationControllers.one.view) 

} 


因此,當我嘗試從MasterSearchViewController(根視圖模態呈現視圖控制器控制器),我得到了上述錯誤。

navigationController?.present(Random200ViewController(), animated: true, completion: nil) 


想法?

+1

獲取app主窗口,然後獲取對根視圖控制器的引用;你應該可以使用它來呈現新的視圖控制器 – ekscrypto

回答

1

這裏有一個方便的功能,您可以添加到任何一段代碼在任何地方呈現視圖控制器你的應用程序:

func showModally(_ viewController: UIViewController) { 
    let window = UIApplication.shared.keyWindow 
    let rootViewController = window?.rootViewController 
    rootViewController?.present(viewController, animated: true, completion: nil) 
} 

我希望它有幫助!

+0

它工作完美,謝謝!這是呈現視圖控制器的首選方式還是在這裏涉及某種程度的「hackery」? – sconewolf

+0

@sconewolf通常,您會從當前呈現的視圖控制器呈現視圖控制器,而不是應用程序的根視圖控制器。有時儘管更簡單,但如果試圖找到當前活動的視圖控制器太麻煩了,這是一個很好的做事方式。 – ekscrypto

+0

如果我以這種方式呈現它,並且想要使用UIViewControllerAnimatedTransitioning對象來創建自定義動畫,哪個視圖控制器需要符合協議並調用持續時間和動畫對象方法?應用程序根目錄? – sconewolf

1

如果你想呈現在你的應用程序的根的viewController,你可以做這樣的:

let rootVC = UIApplication.shared.keyWindow?.rootViewController 

rootVC?.present(Random200ViewController(), animated: true, completion: nil) 
+1

啊,我看@ekscrypto說了上面的同樣的事情。 – clarus

+0

對不起,我在我的移動設備上輸入一個示例源代碼非常乏味,所以我僅限於發表評論。好的工作拿出類似的解決方案! – ekscrypto

+0

你們兩個都保存了我的屁股,我希望我能給2個複選標記,但@ekscrypto在你之前的幾分鐘內插入。但仍然連根拔起,仍然感激你的幫助! – sconewolf

相關問題