您的位置:首页 > 移动开发 > IOS开发

iOS开发之设计模式(一)

2015-12-22 12:49 363 查看
从本篇文章开始,我们将陆续讲解iOS开发中使用到的几种主要的设计模式。本篇文章就简单介绍委托设计模式。

简单理解一下委托模式:就是对象A想要做的操作交给对象B去做,其中对象B就是委托对象。也叫做对象A的代理

不是任何对象都能成为对象A的代理。一个对象要想成为对象A的代理是有条件的,就是要遵循对象A的协议(类似Java接口),遵循协议后还要实现协议中的方法。

对委托模式的理解可为下图:



下面我们来通过一个例子:点击HXRedView上的按钮greenButton,在控制器页面中打印内容。

HXRedView.h

#import <UIKit/UIKit.h>

@<span style="color:#FF0000;">protocol</span> HXRedViewDelegate <NSObject>

@optional
- (void)didClickGreenButton;

@end

@interface HXRedView : UIView
/**
*  代理(委托对象)
*/
<span style="color:#FF0000;">@property (nonatomic, weak) id<HXRedViewDelegate> delegate;</span>

@end

HXRedView.m

#import "HXRedView.h"

@interface HXRedView ()
@property (nonatomic, weak) UIButton *greenButton;

@end

@implementation HXRedView

- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {

self.backgroundColor = [UIColor redColor];

// 创建按钮
UIButton *greenButton = [[UIButton alloc] init];
[greenButton setTitle:@"绿色按钮" forState:UIControlStateNormal];
[greenButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[greenButton setBackgroundColor:[UIColor greenColor]];

[greenButton addTarget:self action:@selector(clickGreenButton) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:greenButton];
self.greenButton = greenButton;
}
return self;
}

/**
*  点击按钮的监听方法
*/
- (void)clickGreenButton {

// 通知代理
if (<span style="color:#FF0000;">[self.delegate respondsToSelector:@selector(didClickGreenButton)]</span>) {// 代理对象实现了协议
<span style="color:#FF0000;">[self.delegate didClickGreenButton];</span>
}
}

/**
*  布局子控件尺寸和位置
*/
- (void)layoutSubviews {
[super layoutSubviews];

self.greenButton.frame = CGRectMake(50, 50, 200, 80);
}

@end

ViewController.m

#import "ViewController.h"
#import "HXRedView.h"

@interface ViewController ()<span style="color:#FF0000;"><HXRedViewDelegate></span>

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// 创建HXRedView对象
HXRedView *redView = [[HXRedView alloc] initWithFrame:CGRectMake(10, 64, 300, 200)];

// 将redView的代理设置为控制器
<span style="color:#FF0000;"> redView.delegate = self;</span>
[self.view addSubview:redView];

}

/**
*  代理(自己)实现协议方法
*/
- (void)didClickGreenButton {
NSLog(@"代理%@实现了协议", self);
}
@end

运行结果:



点击按钮后:



在ViewController.m文件中,创建了HXRedView对象redView之后,设置了redView的代理为控制器

redView.delegate = self;


但是并不是所有对象都能成为redView的代理,控制器要遵循redView的协议才行

@interface ViewController ()<HXRedViewDelegate>


现在代理就可以实现协议中的方法。

Objective-C的协议,类似于C++的抽象类,JAVA的接口。其具体定义如下:

@protocol HXRedViewDelegate<NSObject>

@optional

- (void)didClickGreenButton;

@end

@protocol为协议关键字,HXRedViewDelegate为协议名,didClickGreenButton为协议里的方法。

委托模式就介绍到这里。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: