反向傳值
有 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的背景顏色,是不是很有趣。哈哈,你們試試看。