iOS开发之delegate设计模式

delegate包括3方:委托方、代理方、协议。

协议:一堆方法的声明

下面我们定义一个协议

首先我们创建一个类继UIView(TouchView)

#warning 协议的制定步骤1.定义协议

@class TouchView;

@protocol TouchViewDelegate <NSObject>


@optional(可选择的方法不必实现,默认的是必须实现的方法)

-(void)TouchViewBeganTouched:(TouchView *)touchView;

-(void)TouchViewEndTouched:(TouchView *)touchView;


@end


*************************************************************************

.h中定义协议

@interface TouchView : UIView

#warning 2.给外界通过设置delegate属性的接口

//在定义协议的时候,需要使用assign关键字,防止产生循环引用。

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


@end

在.m中实现协议方法

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

{

//判断代理响应方法

    if (_delegate && [_delegaterespondsToSelector:@selector(TouchViewBeganTouched:)])

    {

        

        [_delegateTouchViewBeganTouched:self ];

        

    }

  

}


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

{

    if (_delegate && [_delegaterespondsToSelector:@selector(TouchViewEndTouched:)])

    {

        

        [_delegateTouchViewEndTouched:self];

    

    }

}

**************************************************************************************

接下来在控制器中创建对象,接收协议并让控制器代理执行协议方法

#import "RootViewController.h"

#import "TouchView.h"


#warning 4.接收协议

@interface RootViewController ()<TouchViewDelegate>//(可以在延展里面接收协议)


@end


@implementation RootViewController


- (void)viewDidLoad {

    [superviewDidLoad];

//    创建一个touchView实例对象,设置delegate

    TouchView *touchview = [[TouchViewalloc]initWithFrame:CGRectMake(100,100, 100,100) ];

    touchview.backgroundColor = [UIColorredColor];

#warning 3.给属性delegate赋值;

    touchview.delegate =self;

    [self.viewaddSubview:touchview];

    [touchview release];

    // Do any additional setup after loading the view.

}

-(void)TouchViewBeganTouched:(TouchView *)touchView

{

    touchView.backgroundColor = [UIColorcolorWithRed:arc4random()%256/255.0green:arc4random()%256/255.0blue:arc4random()%256/255.0alpha:1.0];

}

#warning 5. 实现协议中的方法

-(void)TouchViewEndTouched:(TouchView *)touchView

{

    NSLog(@"哈哈");

}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值