UINavigationControllerの基礎的な使い方

UINavigationControllerの使い方を簡単にまとめます。

UINavigationControllerを定義する

まずは、UINavigationControllerを定義します。
その時、一番最初に表示したいViewのViewControllerを渡します。

TAViewController *viewController = [[TAViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];

initWithRootViewControllerで一番最初のViewを指定しています。

このnavigationControllerをwindowのrootViewControllerに指定します。

self.window.rootViewController = navigationController;

この状態で一度立ち上げてみます。
(わかりやすいように背景をグレーにしています)

f:id:w6500:20131203202628p:plain:w250

中身は何もありませんが、上部にヘッダーの様なエリアができました。
これがUINavigationControllerです。

タイトルを表示する

UINavigationControllerにタイトルを表示します。
UINavigationControllerは表示してあるViewControllerのタイトルを勝手に表示してくれるので、viewControllerのタイトルに値を設定します。

// ViewController内で
self.title = @"view1";

この状態で立ち上げてみます。

f:id:w6500:20131203203031p:plain:w250

遷移させてみる

この一番最初に表示されるViewから別のViewに遷移させてみます。
適当にTableViewを設置し、セルをタップしたら次のページに遷移させてみます。

セルがタップされた時に、navigationControllerのpushViewControllerメソッドを実行します。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 遷移先のViewController
    TASecondViewController *secondViewController = [[TASecondViewController alloc] init];
    [self.navigationController pushViewController:secondViewController animated:YES];
}

f:id:w6500:20131203204136p:plain

まとめ

デフォルトのまま使う分には特に難しくなかったです。
カスタマイズしようとするときっと奥が深いんだろうなと思うので、もう少し触ってみようと思います。