0

I would like to be able to programatically select a tab on a UITabBarController and then access the view that is loaded in order to set the segment loaded by default.

For example if I have a menu and click a button titled 'A/B', I want it to select the 'A' tab, and then the 'B' segment. If I click a button titled 'A/C', I want it to select the 'A' tab and then the 'C' segment.

The first part of the problem I have managed to figure out as follows:

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

I'm not sure how to get the view that is automatically opened though. What is the best way to do this?

Many thanks in advance!

Ben
  • 4,707
  • 5
  • 34
  • 55

1 Answers1

0

In the end, I realised I could get the navigation controller from self.selectedViewController and then the view controller from that using topViewController.

For example, if I have a navigation controller of called NavigationController and a view controller called GroupsViewController, I can do the following:

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
        }
    }
}

Note that I had to set a variable (of type ContentType) to be used in ViewDidAppear rather than accessing the segment control as I had originally planned (because although the tab may be present, the view controller may not have been loaded yet).

Ben
  • 4,707
  • 5
  • 34
  • 55