简体   繁体   中英

Using delegate with tabBarController on Storyboard

Would appreciate any advice as I try and wrap my head around this - I'm not sure if I'm implementing this wrong, or am working from the wrong premise (or both).

If I have a class in which I've created a protocol (the delegatOR) - in order to assign a delegate for that protocol, am I right to say I need to alloc/init the 'delegatee' class somewhere in the delegator's implementation file, and then assign it as the delegator's delegate?

If so, follow up question: I have a tabBarController set up in Storyboard, and when the user clicks on the 'end' tab I'd like to send a message to the viewController for the view they're about to leave, so it pops up an alert saying something like 'are you sure?'. Since storyboard does the initializing and allocating behind the scenes, I'm at a loss as to how to set up the delegate. I read in another posting about using the prepareForSegue method when segueing between two viewControllers to set the delegate, but can't work out a similar catch-and-set technique for the tabBarController.

If I have a class in which I've created a protocol (the delegatOR) - in order to assign a delegate for that protocol, am I right to say I need to alloc/init the 'delegatee' class somewhere in the delegator's implementation file, and then assign it as the delegator's delegate?

No. The way it usually works is that some other class, usually some kind of controller, will instantiate (ie alloc/init) an object as well as its delegate, and set the object's delegate.

For example, if you have a UITableView and a UITableViewDelegate , typically you have some kind of view controller that owns the UITableView , and also owns the UITableViewDelegate (often the view controller itself is the delegate). It's the view controller's job to set the table view's delegate. It most certainly is not the UITableView 's job to create and set its delegate.

Still, you're right that setting delegates for view controllers can be hard when you're using Storyboard. If the prepareForSegue: method isn't working for you, I assume it's because the tab bar controller is your root view controller (as it well should be, according to the HIG). Since your app delegate will have a window property, you should be able to get to the root view controller from it:

UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
tabController.selectedIndex = [defaults integerForKey:kOptionLastTabSelectedKey];
tabController.delegate = self;

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