目标:当点击一个类的视图对象的时候,做一些响应,点击该类不同的视图对象做出的响应不同
而触发时机是点击该视图时,所以在- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event这个方法让代理去执行任务
1.定义协议
@class TouchView;//当定义协议的时候TouchView还没出现
@protocol TouchViewDelegate <NSObject>
//协议中存在四个方法,对应触摸的四个时机,当视图对象接收到不同的触摸事件之后,通过协议中的方法通知代理对象
@optional
- (void)touchViewTouchesBegan:(TouchView *)touchView;
- (void)touchViewTouchesMoved:(TouchView *)touchView;
- (void)touchViewTouchesEnded:(TouchView *)touchView;
- (void)touchViewTouchesCancelled:(TouchView *)touchView;
@end
@interface TouchView : UIView
@property (nonatomic, assign) id<TouchViewDelegate>delegate;
//代理是通过属性的形似出现的
@end
2.遵守协议
@interface DelegateViewController ()<TouchViewDelegate>
@end
3.设置代理
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor cyanColor];
TouchView *redView = [[TouchView alloc]initWithFrame:CGRectMake(20, 50, 280, 40)];
redView.backgroundColor = [UIColor redColor];
redView.tag = 100;
//为视图指定代理,来处理视图的触摸事件
redView.delegate = self;
[self.view addSubview:redView];
[redView release];
TouchView *blueView = [[TouchView alloc]initWithFrame:CGRectMake(20, 120, 280, 40)];
blueView.backgroundColor = [UIColor blueColor];
blueView.tag = 101;
blueView.delegate = self;
[self.view addSubview:blueView];
[blueView release];
//grayView
TouchView *grayView = [[TouchView alloc]initWithFrame:CGRectMake(20, 450, 280, 100)];
grayView.backgroundColor = [UIColor grayColor];
grayView.tag = 102;
grayView.delegate = self;
[self.view addSubview:grayView];
[grayView release];
}
4.让代理做事情的一个时机
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//原理:
//如果代理实现了协议的方法,就让代理调用方法,如果没有实现就不要调用
//判断代理是否实现了对应的方法(判断一个对象是否实现某个特定的方法)
if ([self.delegate respondsToSelector:@selector(touchViewTouchesBegan:)]) {
//触摸开始时通知代理做相应的操作
[self.delegate touchViewTouchesBegan:self];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//respondsToSelector:@selector 返回BOOL类型
if ([self.delegate respondsToSelector:@selector(touchViewTouchesMoved:)]) {
//触摸移动时通知代理做相应的操作
[self.delegate touchViewTouchesMoved:self];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([self.delegate respondsToSelector:@selector(touchViewTouchesEnded:)]) {
//触摸结束时通知代理做相应的操作
[self.delegate touchViewTouchesEnded:self];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([self.delegate respondsToSelector:@selector(touchViewTouchesCancelled:)]) {
//触摸取消时通知代理做相应的操作
[self.delegate touchViewTouchesCancelled:self];
}
}
5.代理做的事情- (void)touchViewTouchesBegan:(TouchView *)touchView
{
//匹配的用switch
switch (touchView.tag) {
case 100:
touchView.backgroundColor = [UIColor randomColor];
break;
case 101:
touchView.superview.backgroundColor = [UIColor randomColor];
break;
case 102:
touchView.center = CGPointMake(arc4random() % 200 + 100, arc4random() % 400 + 100);
break;
default:
break;
}
}