iOS笔记 - 页面传值(代理)


代理传值

1 - delegate 和 block 常用于逆向传值,两者都比较好用,但还是有区别的

① delegate 在写法上比较麻烦,一方必须设置代理,另一方必须遵循代理且实现代理(必须/可实现)

② delegate 的优势:代理的回调函数可以是一组多个函数,在不同的时机调用不同的回调函数;也可以说在一个协议中定义多个方法,在不同的触发事件中执行

2 - block 在写法上比较自由,是一种轻量级的回调,它能够直接访问上下文,使用块的地方和块的实现地方在同一个地方,使得代码组织更加连贯。但是在使用 block 时需要注意防止循环引用,导致内存泄漏的问题

3 - 代码示例:实现第二页面向第一页面传值的功能

// - ViewController.m

 1 #import "ViewController.h"
 2 #import "SecondViewController.h"
 3 @interface ViewController()// 步骤三:接受协议
 4 
 5 @property(nonatomic,strong)UILabel *label;// 显示传过来的值
 6 
 7 @end
 8 
 9 @implementation ViewController
10 
11 - (void)viewDidLoad {
12     [super viewDidLoad];
13 
14     UIButton *nextBT = [UIButton buttonWithType:UIButtonTypeCustom];
15     CGRect frame = nextBT.frame;
16     frame.size.height = 40;
17     frame.size.width = 100;
18     nextBT.frame = frame;
19     nextBT.center = self.view.center;
20     [nextBT setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
21     [nextBT setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
22     [nextBT setTitle:@"下一页" forState:UIControlStateNormal];
23     nextBT.backgroundColor = [UIColor cyanColor];
24     [nextBT addTarget:self action:@selector(pushNextPage) forControlEvents:UIControlEventTouchUpInside];
25     nextBT.layer.cornerRadius = 8;
26     [self.view addSubview:nextBT];
27 
28     self.label = [[UILabel alloc] init];
29     self.label.frame = CGRectMake((self.view.frame.size.width - 200)*0.5, 160, 200, 45);
30     self.label.layer.masksToBounds = YES;
31     self.label.layer.cornerRadius = 8.0f;
32     self.label.textColor = [UIColor whiteColor];
33     self.label.backgroundColor = [UIColor blackColor];
34     [self.view addSubview:self.label];
35 
36 }
37 
38 -(void)pushNextPage{
39 
40     SecondViewController *SecVC = [SecondViewController new];
41     SecVC.delegate = self;
42     [self.navigationController pushViewController:SecVC animated:YES];
43 
44 }
45 
46 
47 // 步骤四:实现代理方法
48 -(void)giveValuesFromNextPage:(NSString *)name{
49     
50     self.view.backgroundColor = [UIColor grayColor];
51     self.label.text = name;// 赋值
52 }
53 
54 @end

// - SecondViewController.h

 1 #import 
 2 
 3 // 步骤一:制定协议
 4 @protocol GivenValues 
 5 // 声明代理方法(只接口)
 6 -(void)giveValuesFromNextPage:(NSString*)name;
 7 
 8 @end
 9 
10 @interface SecondViewController : UIViewController
11 
12 // 步骤二:声明代理
13 @property(nonatomic,weak)iddelegate;
14 
15 @end

// - SecondViewController.m

 1 #import "SecondViewController.h"
 2 @implementation SecondViewController
 3 
 4 - (void)viewDidLoad {
 5     [super viewDidLoad];
 6     self.view.backgroundColor = [UIColor whiteColor];
 7 }
 8 
 9 
10 // 代理传值
11 -(void)dealloc{
12     
13     // 步骤五:回调传值
14     if ([_delegate respondsToSelector:@selector(giveValuesFromNextPage:)]) {
15         [_delegate giveValuesFromNextPage:@"代理传值"];// 谁是代理谁就执行(接受协议/成为代理/实现代理方法)
16     }
17 }
18 
19 @end

运行效果:返回第一页面时显示传过来的值并改变背景色