swift - 选择选项卡并更改加载 View 上的段

标签 swift uitabbarcontroller uitabbar

我希望能够以编程方式选择 UITabBarController 上的选项卡,然后访问加载的 View 以设置默认加载的段。

例如,如果我有一个菜单并单击标题为“A/B”的按钮,我希望它选择“A”选项卡,然后选择“B”段。如果我单击标题为“A/C”的按钮,我希望它选择“A”选项卡,然后选择“C”段。

我设法解决的问题的第一部分如下:

class TabBarController: UITabBarController {
        ...
        func selectTab(name: String) {
            for tab in self.viewControllers! {
                if(name == tab.tabBarItem.title) {
                    self.selectedViewController = tab
                    return
                }
            }
        }
}

我不确定如何获取自动打开的 View 。最好的方法是什么?

非常感谢!

最佳答案

最后,我意识到我可以从self.selectedViewController获取导航 Controller 。然后使用 topViewController 的 View Controller .

例如,如果我有一个名为 NavigationController 的导航 Controller 和一个名为 GroupsViewController 的 View Controller ,我可以执行以下操作:

func selectTab(name: String, contentType: ContentType? = nil) {
    for tab in self.viewControllers! {
        if(name == tab.tabBarItem.title) {
            self.selectedViewController = tab
            if let nc = self.selectedViewController as? NavigationController{
                if let vc = nc.topViewController {
                    if let gvc = vc as? GroupsViewController {
                         gvc.activeContentType = contentType
                    }
                }
            }
            return
        }
    }
}

请注意,我必须设置一个变量(ContentType 类型)以在 ViewDidAppear 中使用。而不是像我最初计划的那样访问段控件(因为虽然选项卡可能存在,但 View Controller 可能尚未加载)。

关于swift - 选择选项卡并更改加载 View 上的段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53881897/

相关文章:

iphone - 如何隐藏标签栏 Controller ?

ios - UIScrollView 不适用于从选项卡栏 Controller 调用的自动布局

ios - 当我在 Telegram 上分享时,如何更改 TintColor 栏按钮项目?

ios - 在执行下一个代码行之前等待任务结束

ios - 如何在 MoreTabBarController 中将 UIStatusBar 颜色更改为 .lightContent

iphone - 如何在 UITabBarController 中获得完全透明的 TabBar

iphone - Storyboard中标签栏的菜单

swift - 主视图的高度在 viewController 之间发生变化。我应该如何保持它们相同?

ios - Swift 3.0 FileManager.fileExists(atPath :) always return false

ios - 使用 dispatch_async 在后台加载图像