代理模式是很常见的一种设计模式,在我们使用UITableView和UICollectionView时,需要设置代理并重写系统提供的代理方法。
代理模式,主要有两方:委托方和代理方
可以简单的理解为:委托方需要做一件事,但是不想自己做,所以需要把这件事委托给其它可以做这件事(协议)的人,也就是代理方,所以委托方需要指明代理方是谁,并且需要告诉代理方在什么情况下去做这件事。
在iOS开发中,抽象成为:对象A为委托方,并制定协议,指定B为代理方,所以B要遵守这个协议,并且需要实现协议的内容也就是要实现协议中的方法。
写一个简单的例子:点击屏幕,让A控制器跳到B控制器,点击屏幕从B回到A,同时改变A的背景颜色,通过代理的方法来实现
简单分析:B回到A的时候让A的背景颜色改变,所以A是实施的一方,即代理方,而B就是委托方。
//控制器A
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "MyViewController.h"
//遵守协议
@interface ViewController ()<MyDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//点击屏幕跳到第二个控制器中
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
MyViewController * vc = [[MyViewController alloc] init];
//设置第二个控制器的代理为第一个控制器对象
vc.delegate = self;
[self presentViewController:vc animated:YES completion:nil];
}
//协议方法,改变第一个控制器的背景颜色
- (void)changeBackgroundColor{
self.view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:0.5];
}
@end
//控制器B
#import <UIKit/UIKit.h>
//制定协议
@protocol MyDelegate <NSObject>
- (void)changeBackgroundColor;
@end
@interface MyViewController : UIViewController
//声明一个代理属性
@property (nonatomic, weak) id <MyDelegate> delegate;
@end
#import "MyViewController.h"
@interface MyViewController ()
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
//点击屏幕
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//回到第一个控制器,并执行协议方法来改变第一个控制器的背景颜色
[self dismissViewControllerAnimated:YES completion:^{
if ([self.delegate respondsToSelector:@selector(changeBackgroundColor)]) {
[self.delegate changeBackgroundColor];
}
}];
}
@end
运行结果