- -(id)init {
- if ([super init] != nil) {
- UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"asdfsadf" p_w_picpath:[UIImage p_w_picpathNamed:@"WWAN5.png"] tag:1];
- self.tabBarItem = item;
- [item release];
- }
- return self;
- }
我不多写关于IOS的文章,写这篇彻底是由于网络上copy,paste的文章太多,将我误导,搞的我花了半天时间才会用这控件,最后仍是看了外国一个英文贴子,才会用。所以写了这篇供后学之人学习加快吧,也但愿你们在写文章时,不要千篇一概的复制、粘贴。咱们是软件工程师,而不是复制、粘贴工程师。css
该文章内容展现效果以下图:网络

接下来,你将看到彻底用代码实现的tab bar选项卡切换效果。下面开始。app
准备工做,建立一个项目名为ViewSwitcher(你能够选择基于View-based Application或Window-based Application,只不过选择后者的话,要本身建立一个view controller罢了,我是选择了第一个)。ide
在此,我不会教你们只在ViewSwitcherAppDelegate中去建立UITabBarController的实例(这种方式网上处处都是),我要教你们如何在本身的view controller中建立UITabBarController实例。oop
下一步,建立两个view controller类,我这里命名为BlueViewController和YellowViewController,固然,它们都是UIViewController的子类。学习
接着,在ViewSwitcherViewController的viewDidLoad方法中,代码以下:url
- tabBar = [[UITabBarController alloc] init];
- tabBar.delegate = self;
- blueViewController = [[BlueViewController alloc] init];
- yellowViewController = [[YellowViewController alloc] init];
- NSArray *viewControllerArray = [NSArray arrayWithObjects:blueViewController,yellowViewController,nil];
- tabBar.viewControllers = viewControllerArray;
- tabBar.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
- [self.view addSubview:tabBar.view];
- [viewControllerArray release];
其中tabBar是在.h文件中声明的UITabBarController对象实例。这样运行看看吧。spa
你会看到为何两个按钮是黑色的呢,没有字呢?没错,由于咱们尚未写这部分代码。设置tab bar标签的图片或文字,能够在它的子view controller中作(这么说或许不是很恰当,由于官方可不这么叫),在这里,我是写在blueViewController和yellowViewController中的,重写它们的init方法,将它们的tabBarItem成员赋值,代码以下:.net
- -(id)init {
- if ([super init] != nil) {
- UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"asdfsadf" p_w_picpath:[UIImage p_w_picpathNamed:@"WWAN5.png"] tag:1];
- self.tabBarItem = item;
- [item release];
- }
- return self;
- }
运行进来 ,你将看到新的效果。orm
那么,那个在item上的小红圈提示是怎么来的呢??咱们实现UITabBarDelegate中的- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController方法,代码以下:
- - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
-
-
- viewController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",80];
-
- }