反向传值
有 a和b两个对象,a中有b(a能访问到b) a给b传值就叫正向传值 。如果b中有a (b不能访问到a),b给a传值叫反向传值。我第一次学的时候也搞不清他们的关系,想必第一次遇见的你,也会大脑短路。今天是情人节,当别人在过节的时候,我们还是好好学习技术,相信技术才能改变世界,那么你首先要改变自己,然后改变周围的人。世界是美好的,我们追求极致的美,然后把这种美分享给同类。我目前就是在做这些事情,我把这种精神传递给你们,由你们传递给更多的人,让他们也参与到学习中来,做出更多优秀美妙的APP,把自己的想法实现。哈哈,啰嗦了点。那么正式开始我们今天的任务,学习反向传值。
代码和上一篇差不多,就是加了个反向传值修改FirstViewController 的背景颜色,刚开始是红色,然后SecondViewController 是黄色,当我们点击SecondViewController里的返回页面时,就把第一页的红色修改成烟青色。 很简单的,那么second就是first的代理,first不需要自己做,把任务让second去实现,然后把实现的效果传递给first,把背景颜色更改了。也就是b是a的代理,b给a传值,但不能访问到a。下面我们来实现代码。
首先创建两个类,FirstViewController和SecondViewController,然后在AppDelegate,创建视图,把视图控制器设为根视图控制器。
然后先来看SecondViewController 里面的设置。首先我们要在SecondViewController .h文件里添加一个方法
然后回到SecondViewController .m文件里面添加2个属性
#import "SecondViewController.h"
#import "FirstViewController.h"//关联firstviewcontroller
@interface SecondViewController ()
//就是这两个属性
@property(nonatomic,weak)id target;
@property(nonatomic,assign)SEL action;
@end
@implementation SecondViewController
//懒加载,等下可以用来调用修改属性
-(void)addTargat:(id)targat action:(SEL)action
{
self.target = targat;
self.action = action;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(30, 50, 300, 40);
[btn setTitle:@"返回上一个视图" forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:22];
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
#pragma clang diagnostic ignored"-Warc-performSelector-leaks" //消除警告
-(void)btnClick
{
//判断下有没有实现这个方法,如果没有实现就调用下面的方法
if ([(NSObject *)self.target respondsToSelector:self.action]) {
//通过调用自身,修改属性,从而修改背景颜色
[(NSObject *)self.target performSelector:self.action withObject:[UIColor cyanColor]];
}
//返回的时候调用这方法,就能修改颜色了
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
//
//然后我们去看FirstViewController
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(30, 50, 300, 40);
[btn setTitle:@"进入下一个视图" forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:22];
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)btnClick
{
SecondViewController *secondVC = [[SecondViewController alloc]init];
//调用secondvc.h里面的方法,让)changeColor:修改背景
[secondVC addTargat:self action:@selector(changeColor:)];
[self presentViewController:secondVC animated:YES completion:nil];
}
//修改自己的背景,因为已经在second里面修改了属性,直接调用就行,不需要亲自修改,由second发消息过来就行
-(void)changeColor:(UIColor *)color
{
self.view.backgroundColor = color;
}
@end
看已经成功修改了firstviewcontroller的背景颜色,是不是很有趣。哈哈,你们试试看。