では、前ページのクラスのデフォルトファイルの内容を見てみましょう。「VCExampleViewController.m」ファイル内のコードは、リスト1のようになっています。
#import "VCExampleViewController.h"
@implementation VCExampleViewController
/*
// The designated initializer. Override to perform setup
// that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:
(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically,
// without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view,
// typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the
// default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)
interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
リスト1のコードでは、既にさまざまなメソッドが定義されており、コメントアウトされているメソッドもいくつかあります。これらのメソッドはすべて、このView Controllerで発生する各種イベントのイベントハンドラです。例えば、このコントローラのビューがメモリにロードされると、viewDidLoadメソッドが実行されます。プログラミングによってビューのUIを作成するには、loadViewメソッドをオーバーライドします。
次に、「VCExampleViewController.xib」ファイルをダブルクリックし、内容を確認します(図5を参照)。[File's Owner]項目がVCExampleViewControllerクラスにマップされています。
[View]項目をダブルクリックし、背景色を緑色に変更し、Buttonビューを追加します(図6を参照)。この時点でInterface Builderでプロジェクトを保存してください。
Xcodeに戻り、「VCExampleViewController.h」ファイルを開き、以下のコードの太字部分を追加します(コードを追加したら、ファイルを保存しておきます)。
#import <UIKit/UIKit.h>
@interface VCExampleViewController : UIViewController {
}
//---declare an action for the Button view---
-(IBAction) displayView:(id) sender;
@end
Interface Builderに戻り、Buttonビューを[File's Owner]項目へ[Control]キーを押しながらドラッグし、[displayView:]を選択します(図7を参照)。
これによって、コードに追加したdisplayView:アクションがButtonビューのTouch Up Insideイベントに接続されます。
今度は、「VCExampleViewController.m」ファイルにコードを追加して、ユーザーがButtonビューをクリックしたときに簡単なアクションが実行されるようにします。これによって、そのアクションがイベントと正しくリンクしていることを確認できます。以下のコード(displayView:メソッド)を追加します。
-(IBAction) displayView:(id) sender{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Button Pressed"
message:@"You have pressed the Button view."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
Xcodeでプロジェクトを保存し、[Command]-[r]キーを押してiPhoneシミュレータでアプリケーションをテストします。Buttonビューを押すと、メッセージが表示されるはずです(図8を参照)。



![図7 イベントの処理:Buttonビューにアクションを接続するには、Buttonビューを[File's Owner]項目へドラッグし、[displayView:]を選択する](http://cz-cdn.shoeisha.jp/static/images/article/4485/7s.gif)
