Set UITabBarController created in Interface Builder as delegate

后端 未结 4 1883
北荒
北荒 2021-01-05 08:33

I created my iOS app with Tab Bar template, so here is UITabBarController with bar buttons. An issue is how to set it as delegate. I found at SO that it has to be set progra

4条回答
  •  悲&欢浪女
    2021-01-05 08:35

    I don't remember exactly the Xcode's Tab Bar template set up, but in your AppDelegate you can access to your window's rootViewController, cast it to a UITabBarController, and then set its delegate to your AppDelegate or to any other view controller.

    Something like this:

    UITabBarController *tabBarController = 
        (UITabBarController *)[[self window] rootViewController];
    [tabBarController setDelegate:self]; // In this example your app delegate would implement the UITabBarControllerDelegate protocol.
    

    EDIT

    If you want to set your ViewController instance as the delegate:

    UITabBarController *tabBarController = 
            (UITabBarController *)[[self window] rootViewController];
    // I assume you have your ViewController instance set as the first view controller of your tab bar controller
    // No need for a cast here since objectAtIndex: returns id, but of course you must implement the UITabBarController protocol in your ViewController.
        [tabBarController setDelegate:[[tabBarController viewControllers] objectAtIndex:0]]];
    

    EDIT 2 From your ViewController itself you can set the tab bar controller's delegate as rdelmar comments. Just keep in mind that this cannot be done in the init method because the view controller is not in the tab bar controller yet. The proper place would be viewDidLoad but therefore it will not be executed until the ViewController view loads...

    self.tabBarController.delegate = self;
    

提交回复
热议问题