UITabBarNavigationにUINavigationController+UITableViewControllerとUIViewControllerを同時に使う

長いタイトルですがタイトルの通りです。UITabBarNavigationにUINavigationController+UITableViewControllerとUIViewControllerを同時に使う。意外とややこしかったのでテンプレでまとめておきました。結構使うのにサンプルが少なかったりします。

結局こういうのを作ります。

プロジェクトはTab Bar Applicationから作ったほうが楽です。
MainWindow.xibの配置がちょっとややこしいです。

AppDelegate.hには

@interface AppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
    IBOutlet UITableViewController * tableViewCon;
    IBOutlet UIViewController * viewCon;
}

としてMainWindow.xibと連携させてください。File's OwnerではなくApp Delegateから関連付けしてください。

あとはAppDelegate.mで実装です。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    tableViewCon = [[UITableViewController alloc]init];
    tableViewCon.title = @"title1";
    tableViewCon.navigationItem.title = @"navi title 1";
    
    viewCon = [[UIViewController alloc]init];
    viewCon.title = @"title2";
    viewCon.navigationItem.title = @"navi title 2";
    
    // tableViewController,viewControllerを配列にしてUITabBarController->setViewControllersに
    NSArray * ar_navs = [[NSArray alloc]initWithObjects:
                       [[UINavigationController alloc] initWithRootViewController:tableViewCon],
                       [[UINavigationController alloc] initWithRootViewController:viewCon]
                       , nil];
    
    // UITabBarControllerをselfにデリゲート、tableViewControllerなどをUITabBarControllerに登録
    UITabBarController * tabBarController = [[[UITabBarController alloc]init] autorelease];
    tabBarController.delegate = self;
    [tabBarController setViewControllers:ar_navs];
    
    // UITabBarControllerを作ってself.window.rootViewControllerに登録
    self.window.rootViewController = tabBarController;
    [self.window makeKeyAndVisible];
    
    return YES;
    
}