通过属性反向传值

对于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<UITouch *> *)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<UITouch *> *)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界面输入的字符串传送回来
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值