簡體   English   中英

嵌入導航控制器時,標簽欄無法識別視圖控制器 swift

[英]Tab Bar not recognising ViewControllers when they are embedded in Navigation Controllers swift

我的界面構建器中有視圖排列(圖片)。

紅色:我的根 TabBarController 繼續...
黃色:我的 UINavControllers 已嵌入...
綠色:視圖控制器

查看排列

我試圖將代碼添加到 TabBarController.swift 以更改我的 ViewControllers.swift 的呈現方式(模態演示代碼)。

在 TabBarController.swift

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if viewController is CreationViewController {
            
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "CreationVC")
            
            controller.modalPresentationStyle = .fullScreen
            self.present(controller, animated: true, completion: nil)
            print("hello")
        } else { print("spaghet") }
    }
}

運行我的應用程序時,當我觸摸 CreationViewController 選項卡欄項時無法識別代碼,即使正在顯示 CreationViewController。 控制台打印“spaghet”而不是“hello”。

所以我換了行

if viewController is CreationViewController

if tabBarController.selectedIndex == 1

現在它可以工作了。 我不明白為什么當我使用“如果 ViewController 是 CreationViewController”時視圖沒有被識別,以及為什么只有當我使用“TabBarController.selectedIndex”時它才被識別。 好像標簽欄 Controller 無法識別它所在的視圖。 順便說一句,我已經在 Interface Builder 中為 ViewController 提供了正確的 class (CreationViewController) 和 Storyboard ID(綠色圈出的那個)

這是因為 UITabBarController 呈現的視圖 controller 實際上是 UINavigationController。 因此,當您檢查它時,它與 class 不匹配

if viewController is CreationViewController

您可以通過簡單地打印從 'func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController)' 獲得的視圖 controller 或在該 function 上放置一個斷點來測試它。

標簽欄 controller 持有UINavigationController ,它可能持有也可能不持有您的CreationViewController

你想像這樣測試它:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {

    // make sure the selected tab contains a UINavigationController
    guard let navVC = viewController as? UINavigationController else {
        print("Selected tab does not contain a navigation controller")
        return
    }
    if navVC.visibleViewController is CreationViewController {
        print("CreationViewController is showing in selected tab's navigation controller")
        // do something
    } else {
        print("Some other controller is showing in selected tab's navigation controller")
        // do something else
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM