当一个类的某些功能需要被别⼈来实现,但是既不明确是些什么 功能,⼜不明确谁来实现这些功能的时候,委托模式就可以派上⽤场。
delegate 设计模式目的是为了降低类之间的耦合性
delegate 是用来解耦的,它不再简简单单让目标去执行一个动作
使用场景
控件有一些列时间点,控制器可以实现这个代理方法,以便在适当 的时机做适当的事
.h文件
@class TouchView;
设置代理
@protocol TouchViewDelegate <NSObject>
当视图被触摸的时候 触发的方法
-(void)touchViewDidTouchBegan:(TouchView *)touchView;
@end
设置代理属性 代理用assign
@interface TouchView : UIView
@property(nonatomic,assign)id<TouchViewDelegate> delegate;
@end
在.m文件
让代理执行协议中的方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//让代理执行协议中的方法
[_delegate touchViewDidTouchBegan:self];
}
在控制器中遵守协议
#import "RootViewController.h"
#import "TouchView.h"
@interface RootViewController ()<TouchViewDelegate>
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(20, 100, 275, 100)];
touchView.backgroundColor = [UIColor redColor];
[self.view addSubview:touchView];
[touchView release];
TouchView *touchView2 = [[TouchView alloc]initWithFrame:CGRectMake(20, 250, 275, 100)];
touchView2.backgroundColor = [UIColor cyanColor];
[self.view addSubview:touchView2];
[touchView2 release];
TouchView *touchView3 = [[TouchView alloc]initWithFrame:CGRectMake(20, 400, 275, 100)];
touchView3.backgroundColor = [UIColor blueColor];
[self.view addSubview:touchView3];
[touchView3 release];
//设置代理
touchView.delegate = self;
touchView2.delegate = self;
touchView3.delegate = self;
//设置tag
touchView.tag = 100;
touchView2.tag = 101;
touchView3.tag = 102;
}
//实现方法
-(void)touchViewDidTouchBegan:(TouchView *)touchView
{
if (touchView.tag == 100) {
NSLog(@"Color");
[self changeColor:touchView];
}else if (touchView.tag == 101)
{
NSLog(@"Posist");
[self changePosist:touchView];
}else if (touchView.tag ==102)
{
NSLog(@"Size");
[self changeSize:touchView];
}
}
-(void)changeColor:(TouchView *)touchView
{
touchView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0];
}
-(void)changePosist:(TouchView *)touchView
{
touchView.center= CGPointMake(arc4random()%(325 - 100 +1)+100, arc4random()%(400-100+1)+100);
}
-(void)changeSize:(TouchView *)touchView
{
touchView.bounds = CGRectMake(0, 0, arc4random()%(275 - 100 +1)+100, arc4random()%(200-100+1)+100);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end