您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 團隊開發:用 UITabBarController 整合多個 Storyboard 的控制器

編輯:iOS 開發綜合

多人協作開發時,常會依功能模組拆成多個 storyboard,各自負責自己那塊的畫面。問題是:最後要怎麼把散落在不同 storyboard 裡的 controller 整合到同一個 UITabBarController 上?

為什麼會有多個 storyboard

多人開發的工程中,依不同的業務模組切分 storyboard 是很合理的做法——每個人負責自己的 storyboard,互不干擾,也大幅降低 merge 衝突。整合的方式其實很簡單:先取得對應的 storyboard,再從中取出你要的 controller 即可。

步驟一:建立繼承自 UITabBarController 的類別

// TabBarController.h
#import <UIKit/UIKit.h>

@interface TabBarController : UITabBarController
@end

步驟二:在實作檔中組裝各 storyboard 的 controller

// TabBarController.m
#import "TabBarController.h"

@interface TabBarController ()
@end

@implementation TabBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSMutableArray *vcs = [NSMutableArray arrayWithCapacity:3];

    // 先取得各個 storyboard
    UIStoryboard *main  = [UIStoryboard storyboardWithName:@"Main"  bundle:[NSBundle mainBundle]];
    UIStoryboard *main1 = [UIStoryboard storyboardWithName:@"Main1" bundle:[NSBundle mainBundle]];
    UIStoryboard *main2 = [UIStoryboard storyboardWithName:@"Main2" bundle:[NSBundle mainBundle]];

    // 依 storyboard 與 storyboard ID 取得各控制器
    UIViewController *vc1 = [main  instantiateViewControllerWithIdentifier:@"xiaoenai"];
    UIViewController *vc2 = [main1 instantiateViewControllerWithIdentifier:@"xinqing"];
    UIViewController *vc3 = [main2 instantiateViewControllerWithIdentifier:@"miyu"];

    [vcs addObject:vc1];
    [vcs addObject:vc2];
    [vcs addObject:vc3];

    // 用新的 controller 陣列取代原本的 viewControllers
    [self setViewControllers:vcs animated:NO];
}

@end

步驟三:別忘了設定 Storyboard ID

使用上述語句之前,必須先在 Identity Inspector 中為每個 View Controller 設定 Storyboard ID,否則 instantiateViewControllerWithIdentifier: 會拿到 nil 甚至直接 crash。

幾個實務上的補充

把 storyboard 名稱抽成常數。字串到處散落是 bug 的溫床,建議集中管理,例如定義 NSString * const kStoryboardMain = @"Main";。

每個 controller 通常要包一層 UINavigationController。若各模組有自己的推疊層級,把 nav controller 當作 tab 的項目會比直接放 view controller 更合理,返回行為才會正常。

用 UITabBarController 的初始設定完成同樣的事。如果這些 controller 之間沒有依賴關係,其實不必寫程式:在 Main.storyboard 上把 UITabBarController 拉出來,按住 control 拖曳到各 controller 建立 relationship segue,Xcode 會自動幫你組好。程式化組裝的價值在於「需要依條件決定 tab 內容」或「tab 由不同 storyboard 提供」的情況。

大團隊可以考慮用 Storyboard Reference。Xcode 支援在 storyboard 之間建立引用,讓每個模組獨立維護自己的 storyboard,主 storyboard 只放一張 reference 佔位,這比純程式碼組裝更直觀,也能保留所見即所得的編輯體驗。

模組化的下一步。當 App 規模再大一點,可以考慮把每個模組的入口封裝成一個註冊表,由主專案依設定決定要載入哪些模組與順序,讓 tab 的組成完全由設定檔驅動,新增模組時不必改動主專案程式碼。

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