2017-06-05 115 views
0

有沒有一種方法可以從UIViewUIViewController的一部分)導航到另一個UIViewController既不使用故事板也不使用導航控制器?從UIView導航到UIViewController沒有故事板和導航控制器

我有一個UITapGestureRecognizer,我想要導航到另一個UIViewControllerBuyController()),每次點擊一次。因此,我的代碼看起來是這樣的:

//handle singleTap 
func singleTapOnLikesDetected(_ sender: UITapGestureRecognizer) { 

    print("check") //works 
    let toController = BuyController() 
    BarController().pushViewController(toController, animated: true) //error occurs since BarController is no navigationcontroller 

} 

BarControllerUITabBarControllerUITabBarControllerDelegate)是我在AppDelegate.swift RootViewController的。然而,UIView屬於另一個UIViewController,稱爲HomeControllerUIViewController,UIScrollViewDelegate)。我根本不使用故事板,我想保持這種狀態,因爲我要在一個團隊中開展一個項目(因此,程序化解決方案將非常受歡迎)...

回答

2

您可以簡單地這樣做是爲了導航,而無需使用navigationController

self.present(toController, animated: true, completion: nil) 

或使用此,

UIApplication.shared.keyWindow?.rootViewController?.present(toController, animated: true, completion: nil) 
+0

我得到一個錯誤說'類型的值「CurrentClass」 [個體經營]沒有成員presentViewController.''presentViewController'似乎已被'present'取代。然而,我得到了同樣的錯誤...如果我用'HomeController()'替換'self',我得到錯誤'嘗試在上呈現,其視圖不是在窗口層次!' – Moritz

+0

查看更新的答案@Moritz – Maddy

+0

您是否在'UIVIEW'子類中添加了這個'func singleTapOnLikesDetected(_ sender:UITapGestureRecognizer)' – Maddy

1

只有UIViewControllers可以提出其他UIViewControllers不是UIViews所以你不會找到了UIView本方法。你也不能用HomeController()替換自己,因爲它創建了一個新的HomeController和它自己的UIView,它沒有被添加到任何其他視圖(如錯誤所示)。

你有幾個選項真的:

1)創建您的UIView協議/委託並HomeController的符合它。然後UIView可以調用協議中的方法,並且HomeController執行實際的切換。

2)你可以得到根視圖控制器來呈現新的UIViewController這樣的:UIApplication.shared.keyWindow?.rootViewController?.present(viewController, animated: true, completion: nil)