delegate包括3方:委托方、代理方、协议。
协议:一堆方法的声明
下面我们定义一个协议
首先我们创建一个类继UIView(TouchView)
#warning 协议的制定步骤1.定义协议
@class TouchView;
@protocol TouchViewDelegate <NSObject>
@optional(可选择的方法不必实现,默认的是必须实现的方法)
-(void)TouchViewBeganTouched:(TouchView *)touchView;
-(void)TouchViewEndTouched:(TouchView *)touchView;
@end
*************************************************************************
.h中定义协议
@interface TouchView : UIView
#warning 2.给外界通过设置delegate属性的接口
//在定义协议的时候,需要使用assign关键字,防止产生循环引用。
@property(nonatomic,assign)id<TouchViewDelegate>delegate;
@end
在.m中实现协议方法-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//判断代理响应方法
if (_delegate && [_delegaterespondsToSelector:@selector(TouchViewBeganTouched:)])
{
[_delegateTouchViewBeganTouched:self ];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (_delegate && [_delegaterespondsToSelector:@selector(TouchViewEndTouched:)])
{
[_delegateTouchViewEndTouched:self];
}
}
**************************************************************************************
接下来在控制器中创建对象,接收协议并让控制器代理执行协议方法
#import "RootViewController.h"
#import "TouchView.h"
#warning 4.接收协议
@interface RootViewController ()<TouchViewDelegate>//(可以在延展里面接收协议)
@end
@implementation RootViewController
- (void)viewDidLoad {
[superviewDidLoad];
// 创建一个touchView实例对象,设置delegate
TouchView *touchview = [[TouchViewalloc]initWithFrame:CGRectMake(100,100, 100,100) ];
touchview.backgroundColor = [UIColorredColor];
#warning 3.给属性delegate赋值;
touchview.delegate =self;
[self.viewaddSubview:touchview];
[touchview release];
// Do any additional setup after loading the view.
}
-(void)TouchViewBeganTouched:(TouchView *)touchView
{
touchView.backgroundColor = [UIColorcolorWithRed:arc4random()%256/255.0green:arc4random()%256/255.0blue:arc4random()%256/255.0alpha:1.0];
}
#warning 5. 实现协议中的方法
-(void)TouchViewEndTouched:(TouchView *)touchView
{
NSLog(@"哈哈");
}