代理模式和target-action模式

   现在开发ios程序都是用mvc模式,view层与control层之间的交互主要用到代理模式和target-action模式。这次讲讲代理模式和target-action的实现方法,作用,及什么情况下使用。

代理模式

            1:定义一个协议:如下代码。

@protocol UIGesturesViewProtocol <NSObject>
@optional
- (void)touchBegindid: (GestureView*)gestureView point:(CGPoint)point;//触摸开始时实现的方法(触摸点)
- (void)touchMovedid:  (GestureView*)gestureView;//触摸移动时出发方法
- (void)touchEnddid:    (GestureView*)gestureView;//触摸结束时出发方法
@end	

   2:在界面(相当于view层)

@interface GestureView : UIView

@property(nonatomic,assign)id<UIGesturesViewProtocol> delegate;

@end





在GestureView中声明一个遵守我们自己定义的协议的属性。
   3:重写继承的

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

如下代码

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    if ([self.delegate respondsToSelector:@selector(touchBegindid: point:)]) {
        [_delegate touchBegindid:self point:[[touches anyObject] locationInView:self.superview]];
    }
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
     if ([self.delegate respondsToSelector:@selector(touchMovedid:)])
         [_delegate touchMovedid:self];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
     if ([self.delegate respondsToSelector:@selector(touchEnddid:)])//判断是否实现该方法如果没有实现则不进行调用函数
         [_delegate touchEnddid:self];
}


4.自己定义一个RootViewController类 遵守UIGesturesViewProtocol协议,实现协议方法。代码如下:

-(void)touchBegindid:(GestureView *)gestureView point:(CGPoint)point{
    NSLog(@"执行了%s,%@",__func__,NSStringFromCGPoint(point));
}
-(void)touchMovedid:(GestureView *)gestureView{
//    NSLog(@"%s",__func__);
}
-(void)touchEnddid:(GestureView *)gestureView{
//    NSLog(@"%s",__func__);
}
以上就是一个完整的代理模式。


Target-action模式

这个模式比较简单学过java的同学都用过invoke,c++ c语言的函数回调,废话不说献上代码:

定义

@property(nonatomic,assign)id target; //类

@property(nonatomic,assign)SEL action; //上边的类调用的方法

实现部分:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.targetperformSelector:self.actionwithObject:selfwithObject:touches];

}

两种方式的比较:

 target-action代理模式
作用:解藕,通常是一系列事件解藕,通常是一系列事件
场景单个事件需要多个事件
   
   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值