新しいView Controllerの追加
このように、View-based Applicationテンプレートを使うと簡単に作業を始めることができます。XIBファイルのViewウィンドウにビューを追加するだけです。今度は、このアプリケーションを編集して、ユーザーがButtonビューを押したときに別のビューに切り替わるようにします。ユーザーの選択に応じて異なるビューを表示することは、非常に一般的なアクションです。この例を学べば、View Controllerの仕組みがさらによく分かります。
同じプロジェクトに新しいView Controllerクラスを追加します。Xcodeで[Classes]グループを右クリックし、新しいファイルの追加を選択します。[Cocoa Touch Classes]グループを選択し、[UIViewController subclass]テンプレートを追加します(図9を参照)。
このView Controllerに「SecondViewController.m」という名前を付けます。
次に、Interface BuilderでUIを作成するために、新しいビューのXIBファイルを追加します。Xcodeで[Resources]グループを右クリックし、新しいファイルを追加します。[User Interfaces]グループを選択し、[View XIB]テンプレートを選択します(図10を参照)。このファイルに「SecondView.xib」という名前を付けます。
追加したファイルがXcodeに表示されます(図11を参照)。
「SecondView.xib」ファイルをダブルクリックしてInterface Builderで編集します。SecondView.xibウィンドウで、[File's Owner]項目を選択し、Identity Inspectorウィンドウを表示します(図12を参照)。この項目のクラスをSecondViewControllerに設定します。
[Control]キーを押しながら[File's Owner]項目を[View]項目へドラッグして、この2つを接続します(図13を参照)。
![図13 ビューの接続:[File's Owner]項目を[View]項目に接続する](http://cz-cdn.shoeisha.jp/static/images/article/4485/13s.gif)
[View]項目をダブルクリックし、背景色をオレンジ色に変更し、Buttonビューを追加します(図14を参照)。
Xcodeで、「SecondViewController.h」ファイルに次のコードを追加します。
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController {
}
//---action for the Return button---
-(IBAction) btnReturn:(id) sender;
@end
Interface Builderに戻り、[Return]ボタンを[File's Owner]項目に接続し、[btnReturn:]を選択します。
ビューの切り替え
ここまでで、新しいView Controllerクラスを追加し、それをXIBファイルに接続しました。今度は、1つ目のビューの[Display SecondView]ボタンを押したときに、2つ目のビューがロードされるように変更します。
「VCExampleViewController.m」ファイルでは、ユーザーがボタンをクリックしたとき、以下のコードの太字部分によって2つ目のView Controllerのビューが現在のビューに追加され、2つ目のビューが表示されます。
#import "VCExampleViewController.h"
//---import the header file for the view controller---
#import "SecondViewController.h"
@implementation VCExampleViewController
SecondViewController *secondViewController;
//---add the view of the second view controller to the current view---
-(IBAction) displayView:(id) sender{
secondViewController = [[SecondViewController alloc]
initWithNibName:@"SecondView"
bundle:nil];
[self.view addSubview:secondViewController.view];
}
- (void)dealloc {
//---release the memory used by the view controller---
[secondViewController release];
[super dealloc];
}
@end
「SecondViewController.m」ファイルでは、btnReturn:アクションのコードを追加して、2つ目のビューを削除し、表示を消し、前のビューが見えるようにします。
#import "SecondViewController.h"
@implementation SecondViewController
-(IBAction) btnReturn:(id) sender {
[self.view removeFromSuperview];
}
これで完了です。[Command]-[r]キーを押してアプリケーションをテストします。[Display SecondView]ボタンを押すと2つ目のビューが表示されるようになりました(図15を参照)。
また、[Return]ボタンを押すと2つ目のビューが消えます。

![図9 Cocoa Touch Classes:[UIViewController subclass]を選択して、新しいView Controllerを追加する](http://cz-cdn.shoeisha.jp/static/images/article/4485/9s.gif)
![図10 XIBファイルの追加:[User Interfaces]グループから[View XIB]ファイルタイプを選択してプロジェクトに新しいビューを追加する](http://cz-cdn.shoeisha.jp/static/images/article/4485/10s.gif)

![図12 クラスの設定:[File's Owner]項目をSecondViewControllerクラスに設定する](http://cz-cdn.shoeisha.jp/static/images/article/4485/12s.gif)

