protocol的简单写法

 //
// TouchView.h
// LessonUIControlAndSubClass #import <UIKit/UIKit.h> @class TouchView;
//1.制定协议,协议名字格式:类名+Delegate
@protocol TouchViewDelegate <NSObject> @optional
- (void)touchBegan:(TouchView *)touchView;
- (void)touchMoved:(TouchView *)touchView;
- (void)touchEnded:(TouchView *)touchView;
- (void)touchCancelled:(TouchView *)touchView; @end @interface TouchView : UIView //2.写属性,属性名delegate,类型是id,并且要遵守协议<类名Delegate>
@property (assign, nonatomic) id<TouchViewDelegate> delegate; @end

 //
// TouchView.m
// LessonUIControlAndSubClass
// #import "TouchView.h" @implementation TouchView //3.一旦找到代理,让代理执行事情
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//判断delegate是否实现了某方法
if ([_delegate respondsToSelector:@selector(touchBegan:)]) {
[_delegate touchBegan:self];
}
} - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if ([_delegate respondsToSelector:@selector(touchMoved:)]) {
[_delegate touchMoved:self];
}
} - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if ([_delegate respondsToSelector:@selector(touchEnded:)]) {
[_delegate touchEnded:self];
}
} - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
if ([_delegate respondsToSelector:@selector(touchCancelled:)]) {
[_delegate touchCancelled:self];
}
} @end
上一篇:Hopfield神经网络和TSP问题


下一篇:Android使用NumberPicker控件实现选择城市,生日