首页 > 解决方案 > 访问嵌入在 UIViewController 中的 UITabBarController

问题描述

我在 UIViewController 中嵌入了一个 UITabBarController。我正在尝试从父 UIViewController 访问 UITabBarController 实例。

vc.children 的返回类型为 [UIViewController],因此 UITabBarController 不会出现。

vc.tabBarController 为 nil,因为视图未嵌入 TabBarController。我的设置是相反的。

有任何想法吗?

我的故事板: 故事板

标签: iosswiftuiviewcontrollerstoryboarduitabbarcontroller

解决方案


Fastest solution:
vc.children.compactMap({$0 as? UITabBarController}).first .

Best solution:
Select the Embed Segue from the storyboard and give an identifier (say "containerEmbedSegue". Next, in your vc:

var tabBarVC: UITabBarController?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "containerEmbedSegue" {
        self.tabBarVC = segue.destination as? UITabBarController
    }
}

推荐阅读