iOS中的委托和代理模式

来源:互联网 发布:掏耳朵 知乎 编辑:程序博客网 时间:2024/06/01 21:45
  • 什么是代理设计模式?—>简单来讲,代理就是实现消息传递的,当然与此同时我们还可以选择通知,KVO,block来实现这一过程
  • 什么时候使用代理设计模式?—>当然就是在需要完成信息传递的时候,就去使用

怎样写一个代理设计模式?

  • 要明确你的协议名称,一般来讲名称都是:控件类名 + Delegate
  • 代理方法中一般都是声明为@optional(程序默认情况下是@required)
  • 代理方法名一般以控件开头
  • 代理方法至少有一个参数

先来了解一个方法:-(BOOL) respondsToSelector: selector 用来判断一个对象是否有以某个名字命名的方法(被封装在一个selector的对象里传递)

下面出示代码来讲解:

#import <UIKit/UIKit.h>@class SSbutton;@protocol SSbuttonDelegate <NSObject>-(void)buttonWith:(SSbutton*)button;@end@interface SSbutton : UIView@property(nonatomic,assign)id<SSbuttonDelegate> delegate;@end
#import "SSbutton.h"@implementation SSbutton-(instancetype)initWithFrame:(CGRect)frame{    self=[super initWithFrame:frame];    if (self) {        UIButton* btn1=[[UIButton alloc] init];        btn1.frame=CGRectMake(0, 0, self.frame.size.width/2, self.frame.size.height);        [btn1 addTarget:self action:@selector(choose) forControlEvents:UIControlEventTouchUpInside];        btn1.backgroundColor=[UIColor redColor];        [self addSubview:btn1];        UIButton* btn2=[[UIButton alloc] init];        btn2.frame=CGRectMake(0, self.frame.size.width/2, self.frame.size.width/2, self.frame.size.height);        btn2.backgroundColor=[UIColor greenColor];        [self addSubview:btn2];    }    return self;}-(void)choose{    if ([_delegate respondsToSelector:@selector(buttonWith:)]) {        [_delegate buttonWith:self];    }}
#import "ViewController.h"#import "SSbutton.h"@interface ViewController ()<SSbuttonDelegate>@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    self.view.backgroundColor=[UIColor yellowColor];    SSbutton* btn=[[SSbutton alloc] initWithFrame:CGRectMake(40, 80, 100, 100)];    btn.delegate=self;    [self.view addSubview:btn];}-(void)buttonWith:(SSbutton *)button{    NSLog(@"btn1");}

iOS中,代理模式设计在控件中用的比较多:在控件类定义协议,代理是它的成员属性,使用控件的控制器一般来实现控件的协议方法,成为控件的代理。当控件发生某些事件的时候,控件利用代理的方法来通知控制器来执行。

0 0
原创粉丝点击