您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 實作筆記:TabBar 嵌套 Navigation 的完整結構(二)

編輯:iOS 相關資訊

絕大多數 App 的主結構都是「TabBarController 包 NavigationController 包 ContentViewController」。本文以自訂 tabbar 為例,示範這個三層結構的建立方式。

一、建立一個共用的導航控制器子類別

// BaseNavigationViewController.h
@interface BaseNavigationViewController : UINavigationController
@end

// BaseNavigationViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];

    if ([self.navigationBar respondsToSelector:
            @selector(setBackgroundImage:forBarMetrics:)]) {
        [self.navigationBar setBackgroundImage:
            [UIImage imageNamed:@"navigationbar_background.png"]
                       forBarMetrics:UIBarMetricsDefault];
    }
}

抽成子類別的好處是:所有分頁共用同一套導航列樣式,日後要改只需改一處,不必在每個頁面重複設定。

二、初始化各分頁並包裝

#import "HomeViewController.h"
#import "NewsViewController.h"
#import "FriendsViewController.h"
#import "PlazaViewController.h"
#import "MoreViewController.h"
#import "BaseNavigationViewController.h"

- (void)_initViewControllers {
    NSArray *vcs = @[
        [[HomeViewController alloc] init],
        [[NewsViewController alloc] init],
        [[FriendsViewController alloc] init],
        [[PlazaViewController alloc] init],
        [[MoreViewController alloc] init]
    ];

    NSMutableArray *navArray = [NSMutableArray arrayWithCapacity:5];
    for (UIViewController *vc in vcs) {
        BaseNavigationViewController *nav =
            [[BaseNavigationViewController alloc] initWithRootViewController:vc];
        [navArray addObject:nav];
    }
    self.viewControllers = navArray;
}

三、自訂 TabBar

- (void)_initTabbarView {
    _tabbarView = [[UIView alloc] initWithFrame:
        CGRectMake(0, kScreenHeight - 49, 320, 49)];
    _tabbarView.backgroundColor =
        [UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar_background.png"]];
    [self.view addSubview:_tabbarView];

    NSArray *normalImages = @[@"tabbar_home.png", @"tabbar_message_center.png",
        @"tabbar_profile.png", @"tabbar_discover.png", @"tabbar_more.png"];
    NSArray *hiImages = @[@"tabbar_home_highlighted.png",
        @"tabbar_message_center_highlighted.png",
        @"tabbar_profile_highlighted.png",
        @"tabbar_discover_highlighted.png",
        @"tabbar_more_highlighted.png"];
    NSArray *titles = @[@"首頁", @"消息", @"好友", @"廣場", @"更多"];

    for (int i = 0; i < normalImages.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake((320 / 5 - 30) / 2 + (64 * i), (49 - 30) / 2, 30, 40);
        button.tag = i;
        [button setImage:[UIImage imageNamed:normalImages[i]]
                forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:hiImages[i]]
                forState:UIControlStateHighlighted];
        button.imageEdgeInsets = UIEdgeInsetsMake(-20, 0, 0, 0);

        [button setTitle:titles[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:10];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor]  forState:UIControlStateHighlighted];
        button.titleEdgeInsets = UIEdgeInsetsMake(20, 0, 0, 0);

        [button addTarget:self action:@selector(tabTapped:)
         forControlEvents:UIControlEventTouchUpInside];
        [_tabbarView addSubview:button];
    }
}

- (void)tabTapped:(UIButton *)button {
    self.selectedIndex = button.tag;   // 讓自訂按鈕具備 tabbar 的切換能力
}

最後記得在 viewDidLoad 中隱藏系統 tabbar,否則會出現兩條:

[self.tabBar setHidden:YES];
[self _initViewControllers];
[self _initTabbarView];

四、AppDelegate 掛上根控制器

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    MainViewController *mainVC = [[MainViewController alloc] init];
    self.window.rootViewController = mainVC;
    [self.window makeKeyAndVisible];
    return YES;
}

五、這個實作值得改進的地方

1. 不要自訂 tabbar。 除非有強烈的品牌視覺需求,否則自訂 tabbar 會失去 iOS 的無障礙支援、Dynamic Type、以及 selectedIndex 之外的所有系統行為。若只是要換色,用 UITabBarAppearance 的 styling 與 itemPositioning 就能解決。

2. 座標不要硬編碼。 範例中的 320、49、64、30 都應改為依 self.view.bounds 與螢幕尺寸計算,否則在 iPhone 5 以後的機型上會錯位。

3. 選中態應改用 selected 而非 highlighted。 自訂 tabbar 若只用 highlighted,切換後按鈕會一直保持高亮,因為 UIButton 不會自動維護「當前選中」狀態。應在 tabTapped: 中遍歷更新各按鈕的 selected 屬性,並改用 forState:UIControlStateSelected 設定圖示。

4. 更現代的替代方案。 iOS 18 起可考慮 UITabBarController 搭配 UITab 的新 API;若只是想要側邊或底部導覽,UISplitViewController 與 sidebar 樣式也值得評估。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved