原文連結:http://blog.csdn.net/hb308102796/article/details/6445227
[cpp] view plaincopy
- -(id)init {
- if ([super init] != nil) {
- UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"asdfsadf" image:[UIImage imageNamed:@"WWAN5.png"] tag:1];
- self.tabBarItem = item;
- [item release];
- }
- return self;
- }
我很少寫關於IOS的文章,寫這篇完全是因為網路上copy,paste的文章太多,將我誤導,搞的我花了半天時間才會用這控制項,最後還是看了外國一個英文貼子,才會用。因此寫了這篇供後學之人學習加快吧,也希望大家在寫文章時,不要千篇一律的複製、粘貼。我們是軟體工程師,而不是複製、粘貼工程師。
該文章內容展示效果如:
接下來,你將看到完全用代碼實現的tab bar選項卡轉場效果。下面開始。
準備工作,建立一個項目名為ViewSwitcher(你可以選擇基於View-based Application或Window-based Application,只不過選擇後者的話,要自己建立一個view controller罷了,我是選擇了第一個)。
在此,我不會教大家只在ViewSwitcherAppDelegate中去建立UITabBarController的執行個體(這種方式網上到處都是),我要教大家如何在自己的view controller中建立UITabBarController執行個體。
下一步,建立兩個view controller類,我這裡命名為BlueViewController和YellowViewController,當然,它們都是UIViewController的子類。
接著,在ViewSwitcherViewController的viewDidLoad方法中,代碼如下:
[cpp] view plaincopy
- 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對象執行個體。這樣運行看看吧。
你會看到為什麼兩個按鈕是黑色的呢,沒有字呢?沒錯,因為我們還沒有寫這部分代碼。設定tab bar標籤的圖片或文字,可以在它的子view controller中做(這麼說或許不是很恰當,因為官方可不這麼叫),在這裡,我是寫在blueViewController和yellowViewController中的,重寫它們的init方法,將它們的tabBarItem成員賦值,代碼如下:
[css] view plaincopy
- -(id)init {
- if ([super init] != nil) {
- UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"asdfsadf" image:[UIImage imageNamed:@"WWAN5.png"] tag:1];
- self.tabBarItem = item;
- [item release];
- }
- return self;
- }
運行進來 ,你將看到新的效果。
那麼,那個在item上的小紅圈提示是怎麼來的呢??我們實現UITabBarDelegate中的- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController方法,代碼如下:
[cpp] view plaincopy
- - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
- // [self.view addSubview:viewController.view];
- // tabBarController.selectedViewController = viewController;
- viewController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",80];
- // viewController.tabBarItem.title = @"aaa";
- }