对于ios开发者来说,反向传值再熟悉不过了。我们通常使用,代理,通知,block进行反向传值,今天我们通过demo一起看一下属性反向传值。例如A界面跳转到B界面。再从B界面往A界面传值。关键点在于B界面如何拿到跳过来的那个A界面。
AViewController.h @interface AViewController : UIViewController //声明一个公开的属性 用于接收 B界面回传的内容 @property(nonatomic)NSString *backVlaue; @end AViewController.m //懒加载lable -(UILabel *)label { if(!_label) { _label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 100)]; _label.font = [UIFont systemFontOfSize:24]; _label.backgroundColor = [UIColor yellowColor]; _label.text = @"初始内容"; [self.view addSubview:_label]; } return _label; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { BViewController *bVC = [[BViewController alloc]init]; //将自己的地址给bVC中avc属性赋值 ,在bVC中通过avc这个属性,就可以找到当前对象 bVC.avc = self; [self presentViewController:bVC animated:YES completion:nil]; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; [self label]; } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (!self.backVlaue) { return; } //将传回的内容显示出来 self.label.text = self.backVlaue; } BViewController.h @interface BViewController : UIViewController //声明一个属性 用来保存前面 AVC实例的属性 @property(nonatomic)AViewController *avc; @end BViewController.m -(UITextField *)field { if (!_field) { _field = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 200, 100)]; _field.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_field]; } return _field; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //把输入的内容传回到前面界面 //获取文本框中的内容 //NSString *content = self.field.text; //将内容创给 AVC (首先要找到AVC的实例) self.avc.backVlaue = self.field.text; [self dismissViewControllerAnimated:YES completion:nil]; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor greenColor]; [self field]; }
如图可以成功将B界面输入的字符串传送回来