iOS Delegate传值 协议两个页面反向传值

Delegate本身是一个设计模式,它的意思是委托别人去做某事。

比如:两个类之间的传值,类A调用类B的方法,类B在执行过程中遇到问题通知类A,这时候我们需要用到代理(Delegate)。

又比如:控制器(Controller)与控制器(Controller)之间的传值,从A跳转到B,再从B返回到A时需要通知A更新UI或者是做其它的事情,这时候我们就用到了代理(Delegate)传值。

例子是A页面跳转B页面,B页面返回给A页面传值.

1.在B页面的.h文件中:

//定义协议与方法
@protocol DeliverDetegate <NSObject>

- (void)setValue:(NSString *)string;

@end

@interface BViewController : UIViewController

//声明委托变量
@property (weak,nonatomic) id<DeliverDetegate>B_Delegate;

@end

2.在B页面的.m中:

@interface BViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) IBOutlet UITextField *DeliverText;

@end
- (IBAction)DeliverAction:(id)sender {

    //通过委托变量调用委托方法
    //_DeliverText.text为传的值
    [self.B_Delegate setValue:_DeliverText.text];
    [self.navigationController popViewControllerAnimated:YES];
}

3.在A页面的.h中:

#import "AViewController.h"
#import "BViewController.h"

@interface AViewController ()<DeliverDetegate>

@property (strong, nonatomic) IBOutlet UILabel *TextLabel;

@end

4.在A页面的.m中:

- (IBAction)ReceiveAction:(id)sender {
    //遵循协议
    BViewController*BVC = [[BViewController alloc]init];
    BVC.B_Delegate = self;
    [self.navigationController pushViewController:BVC animated:YES];
}
//实现委托方法,即实现的setValue方法
- (void)setValue:(NSString *)string
{
    NSLog(@"A接收到B数据%@",string);
    _TextLabel.text = string;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值