protocolの簡単な書き方

6851 ワード

 1 //

 2 //  TouchView.h

 3 //  LessonUIControlAndSubClass

 4 

 5 

 6 

 7 #import <UIKit/UIKit.h>

 8 

 9 @class TouchView;

10 //1. , : +Delegate

11 @protocol TouchViewDelegate <NSObject>

12 

13 @optional

14 - (void)touchBegan:(TouchView *)touchView;

15 - (void)touchMoved:(TouchView *)touchView;

16 - (void)touchEnded:(TouchView *)touchView;

17 - (void)touchCancelled:(TouchView *)touchView;

18 

19 @end

20 

21 @interface TouchView : UIView

22 

23 //2. , delegate, id, < Delegate>

24 @property (assign, nonatomic) id<TouchViewDelegate> delegate;

25 

26 @end
 1 //

 2 //  TouchView.m

 3 //  LessonUIControlAndSubClass

 4 //

 5 

 6 #import "TouchView.h"

 7 

 8 @implementation TouchView

 9 

10 //3. , 

11 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

12     // delegate 

13     if ([_delegate respondsToSelector:@selector(touchBegan:)]) {

14         [_delegate touchBegan:self];

15     }

16 }

17 

18 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

19     if ([_delegate respondsToSelector:@selector(touchMoved:)]) {

20         [_delegate touchMoved:self];

21     }

22 }

23 

24 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

25     if ([_delegate respondsToSelector:@selector(touchEnded:)]) {

26         [_delegate touchEnded:self];

27     }

28 }

29 

30 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {

31     if ([_delegate respondsToSelector:@selector(touchCancelled:)]) {

32         [_delegate touchCancelled:self];

33     }

34 }

35 

36 @end