#import <UIKit/UIKit.h>
#import "CustomView.h"
@interface CustomViewController : UIViewController <CustomViewDelegate>
@end
このクラスでは,CustomVIewデリゲートを実装します.それを宣言するために,
UIViewControllerの後に<CustomViewDelegate>を記述しています.
これは,CustomViewController.hファイルの中に記述したデリゲートの名前になります.
次にCustomViewController.mです.
- (void)viewDidLoad
{
[super viewDidLoad];
CustomView *customView = [[CustomView alloc] initWithFrame:self.view.bounds];
[customView setDelegate:self];
[self setView:customView];
}
- (void)didOKButtonTouched:(UIButton *)button{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Touched!!"
message:@"OK Buttou is Touched"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
}
viewDidLoadでは,CustomViewのインスタンスをCustomViewControllerのviewプロパティに設定しているだけです.
さて,先程,CustomViewController.hの中で,このクラスはCustomViewDelegateを実装することを宣言したので,
その関数を記述する必要があります.
CustomView.hファイルの中でデリゲートメソッドの名前を
didOKButtonTouched:button
と指定しましたので,その名前のメソッドを実装します.
これで全てが完了しました.実行してみましょう.
ボタンを押すとアラートがでましたか?
このように処理を他のクラスに委任できることがメリットです.
次の記事へ
HOMEに戻る