简体   繁体   中英

Is it possible to set a coordinator property on a UITabBarController?

I'm trying to implement a slide out menu in my tab-based app. I have a container controller which holds the MenuViewController and the UITabBarController, and it conforms to a MasterDelegate protocol which tells the container to slide out the MenuViewController when the hamburger button located on an individual tab is pressed. My problem is that the coordinator property for the UITabBarController is not set until after the UITabBarController is configured, and thus the property in the UITabBarController as well as the ViewController for the tab containing the button is always nil.

Here is the code belonging to the container that sets up the UITabBarController:

func configureHomeController() {

    centerController = MainTabBarController()

    // Make sure to set delegate of homeController
    centerController.masterDelegate = self

    print("MainContainterController: Setting the MainTabBarController delegate")

    if centerController.masterDelegate != nil {
    print("MainContainerController: MainTabBarController Delegate set")
    }

    view.addSubview(centerController.view)

    // Add the navigationController containing the HomeController as a child to the ContainerController
    addChild(centerController)

    // Home controller didMove to the parent container of self, which is the ContainerController
    centerController.didMove(toParent: self)
}

In the TabBarController, there is a print statement that executes after the TabBarController is configured which tells me if the masterDelegate property is nil or not. This is printed before the container controller prints the two above statements. Since the 2nd print statement is printed, I know that the coordinator is being set, but it's set too late.

My question is how do I get the masterDelegate to be set before the UITabBarController is done being configured? Or is there a way to set that property after the fact?

Create a convenience init for your tabbarcontroller and pass the delegate to it. Something like this:

convenience init(masterDelegate: MasterDelegate) {
    self.init(nibName: nil, bundle: nil)

    self.masterDelegate = masterDelegate
}

the when you are setting up the TabBarController, instantiate it like this:

   centerController = MainTabBarController(masterDelegate: self)
   centerController.configure()

Also, make a configure function in MainTabBarController. In there, set up your viewControllers.

 (in MainTabBarController)
   func configure() {
       viewControllers = [viewController, viewController2, ....]
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM