I'm trying to add a UIButton to UITabBar in my iPad application with following code:
TabBarAppDelegate *delegate = (TabBarAppDelegate *)[[UIApplication sharedApplication] delegate];
UITabBarController *tabbar = (UITabBarController *)delegate.window.rootViewController;
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[tabbar.view addSubview:b];
tabbar
is OK and referencing to a correct tabbar item (say, I can switch active tab with following code: [tabbar setSelectedIndex:1];
).
This code is called by some other custom button. Though there are no errors in开发者_开发问答 the log, the button doesn't show on the tabbar :(
What am I doing wrong and what is a right way to add UIButton to UITabBar? :) Here is an example:
http://gyazo.com/99fc0df0ed47dd6be91b558161cab4f9.png
Thanks in advance!
Edit: OK, if I'll stick to UIToolbar option, then what is a right way to switch between views? Create an NSArray of ViewContollers and load corresponding ViewController's view to an active View?
You cannot add a UIButton
directly to a UITabBarController
. From the UITabBarController
Class Reference:
You should never access the tab bar view of a tab bar controller directly.
Further along, the documentation reads:
Tab bar items are configured through their corresponding view controller. To associate a tab bar item with a view controller, create a new instance of the UITabBarItem class, configure it appropriately for the view controller, and assign it to the view controller’s tabBarItem property. If you do not provide a custom tab bar item for your view controller, the view controller creates a default item containing no image and the text from the view controller’s title property.
Therefore your two options are:
- Create a
UITabBarItem
(documentation) and add that. - Use a
UIToolBar
instead, but remember to addUIBarButtonItem
s.
Although the OP has decided to use a UIToolBar to solve this, I thought I would post a quick response suggesting another option for anyone reading this. Basically, you can do this, but what you have to do is subclass the UITabBarController, and create your UIButton(s) and add them in the subclass. Anyhow, here are a couple of links that provide details.
Here and Here
Just in case someone stumbles over this old question: You probably want to have a look at the respective delegates of UITabBar
and UITabBarController
(UITabBarDelegate
and UITabBarControllerDelegate
).
精彩评论