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 programmatically in AppDelegate, but I believe it's impossible, because I've got no access to Tab Bar Controller as outlet.
I added proper value to @interface
(both ViewController and AppDelegate), but doesn't know what to do next.
@interface ViewController : UIViewController <UITabBarControllerDelegate>
I hope I don't have to get rid of whole app template and it's possible to set Tab Bar Controller created in IB to be delegate.
Exactly I want to make it delegate to create on tab select event like this:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
Any idea?
What about create a
viewController
lets sayMyTabController
subclassUITabBarController
and set the tab Controller's class in you
storyboard
toMyTabController
instead ofUITabBarController
, then putself.delegate = self;
in yourviewDidLoad
implement:
and here you are.
Edit:
If you find
self.delegate = self;
is odd, which it is, you can create an outlet in yourMyTabController
Then you can put
tabBarController.delegate = self;
0 lines of code
Drag an Object and subclass it
TabBarControllerDelegate
.Set delegate to that Object
Put your existing code in that Object
This is the code you already have in your current
UITabBarControllerDelegate
.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 aUITabBarController
, and then set its delegate to your AppDelegate or to any other view controller.Something like this:
EDIT
If you want to set your ViewController instance as the delegate:
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...You can quickly and easily create a new TabBarController Delegate class and connect it as the delegate in the storyboard.
Create a new class :
class TabBarControllerDelegate: NSObject, UITabBarControllerDelegate {
In IB, add an object from the object library to the list of View Controller on the left (note: search "object", it's a yellow cube).
Change the class of this object (your yellow cube in IB) to TabBarControllerDelegate
In IB navigate to your Tab Bar Controller Scene. From the Connection Inspector, drag the delegate circle to the new object you added in Step 3.
Implement your delegate methods in your TabBarControllerDelegate class. Done!
}