Delegateはとても重要な概念なので文字サイズも大きくしています笑
さて,このDelegateという単語.初めてではありませんよね?
そう,プロジェクトを作成すると必ずできる
「AppDelegate」ファイルで見ていますよね.
じゃあDelegateとはなんぞや!!
我らがグーグル先生に聞くと,
「委譲,委託」
なんて答えが返ってきます.
意味不明ですね.
delegateとは,ある処理Aが行われた際に,その後の処理を関数Fに「委譲」する仕組みのことです.
意味不明ですね.
delegateとは,例えば!!!
アプリが起動した際に,起動した後の処理を関数
意味不明ですね.
delegateとは,例えばぁぁぁぁああああ!!!!
ボタンを押した際に,その後の処理を関数
意味不明ですね.
もう伝わる気がしないので,コードかきます!!どーん!!
今回は
CustomViewController : Subclass of UIViewController
CustomView : Subclass of UIView
の2つのクラスを作成してください.
次にCustomView上にボタンを一つ置きます.
このボタンがタッチされたことをdelegateを用いてCustomViewControllerに通知します.
さて,まずCustomViewから見てみましょう.
CustomView.h
@protocol CustomViewDelegate <NSObject>
- (void)didOKButtonTouched:(UIButton *)button;
@end
@interface CustomView : UIView
@property (nonatomic, unsafe_unretained) id<CustomViewDelegate> delegate;
@end
まず,このデリゲートの名前を決めます.
CustomViewDelegateが一番分かりやすい名前じゃないでしょうか!!
次に,デリゲートするための関数名を記述します.
今回は,CustomView上のボタンが押されたことを通知するための関数なので,
「didOKButtonTouched」とでもしましょうか.
次に,デリゲート先のオブジェクトを管理する変数を宣言します.
これは,プロパティとして宣言します
id<CustomViewDelegate> delegate
これは,id型の変数で「CustomViewDelegate」を実装している変数「delegate」という意味です.
次はCustomView.mを見ていきます.
@implementation CustomView
@synthesize delegate;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self setBackgroundColor:[UIColor colorWithRed:0.5 green:0.0 blue:1.0 alpha:0.1]];
CGFloat frameWidth = self.frame.size.width;
CGFloat frameHeight = self.frame.size.height;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(frameWidth / 2 - 50, frameHeight / 2 - 25, 100, 50)];
[button setTitle:@"OK" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchDown];
[self addSubview:button];
}
return self;
}
- (void)buttonTouched:(UIButton *)button{
[self.delegate didOKButtonTouched:button];
}
@end
UIViewの上にボタンを乗せているだけです.難しいコードではありません.
さて,ボタンが押された時の処理について見てみましょう.
先程設定したプロパティのメソッドを呼び出しています.
プロパティの「delegate」は
id型の変数で「CustomViewDelegate」を実装している変数
でしたよね!!
デリゲート「CustomViewDelegate」を実装しているということは,
- (void)didOKButtonTouched;
を実装しているということになります.
なので,そのメソッドを呼び出しているわけなんですね.
なんとなく,お分かり頂けましたか??
次のエントリではCustomViewControllerを見ていきます.
次の記事へ
HOMEに戻る