我希望能够以编程方式选择 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/