Delegate 设计模式

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];
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值