Delegate设计模式
/** * 代理和协议的使用: * 当自定义协议时的步骤: * 1. 定义协议.(协议中存放的代理应该完成的任务) * 2. 定义代理属性(存储外界的代理对象) * 3. 在其他文件中指定代理对象 * 4. 代理对象所属的类, 服从对应的协议(答应干活) * 5. 实现协议中的方法(代理来干活) * 6. 委托方(协议的制定者)通知代理执行协议中的方法(让代理去干活) * */
Delegate 设计模式的使用过程
1 . 对我们的 View 写协议.
针对触摸事件写处理方法(4个)
@protocol TouchViewDelegate
@optional
- (void)handleTouchBegan:(TouchView *)aView;//对应 touchesBegan 时机
- (void)handleTouchMoved:(TouchView *)aView;//对应 touchMoved 时机
- (void)handleTouchEnded:(TouchView *)aView;//对应 touchEnded 时机
- (void)handleTouchCancelled:(TouchView *)aView;//对应 touchCancelled 时机
@end
2 . 在 view 的.h文件中, 定义代理属性
@property (nonatomic, assign) id delegate;
3 . 在视图控制器中服从代理, 并且实现协议中方法
- (void)handleTouchEnded:(TouchView *)aView {
aView.center = CGPointMake(arc4random() % 335, arc4random() % 500);
}
4 . 在视图控制器中指定 View 对象的代理
TouchView *redView = [[TouchView alloc] initWithFrame:CGRectMake(20, 20, 335, 100)];
redView.backgroundColor = [UIColor redColor];
redView.delagate = self;
[self.view addSubview:redView];
[redView release];
5 . 在响应触摸事件的方法中, 调用协议中的方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//6. 让代理执行任务
if ([self.delagate respondsToSelector:@selector(handleTouchBegan:)]) {
[self.delagate handleTouchBegan:self];
}
}