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;
}