** 代理的主要组成部分:**
协议:用来指定双方可以做什么,必须做什么;
委托对象:根据指定的协议,指定代理去完成什么功能;
代理对象:根据指定的协议,完成委托方需要实现的功能;
使用代理实现界面间的传值(逆传):
创建委托界面B,代码如下:
.h文件
#import <UIKit/UIKit.h>//新建一个协议,协议的名称一般是由:"类名+Delegate"
@protocol ViewControllerBDelegate<NSObject>//代理方必须实现的方法@required//代理方可选实现的方法@optional- (void)ViewControllerBsendValue:(NSString *)value;
@end@interface ViewControllerB : UIViewController//委托代理人,为了避免造成循环引用,代理一般需使用弱引用
@property(weak,nonatomic) id<ViewControllerBDelegate> delegate;@end
.m文件
#import "ViewControllerB.h"
@interface ViewControllerB ()
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *btn;
@end
@implementation ViewControllerB
- (IBAction)btnClick:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
if ([_delegate respondsToSelector:@selector(ViewControllerBsendValue:)])
{ //如果协议响应了sendValue:方法 //通知代理执行协议的方法
[_delegate ViewControllerBsendValue:_textField.text];
}
}
创建代理界面A:
.m文件
#import "ViewController.h"
#import "ViewControllerB.h"
@interface ViewController ()<ViewControllerBDelegate>
@end@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}
- (void)ViewControllerBsendValue:(NSString *)value
{ //创建一个警告框,来显示从B传过来的值
UIAlertController* alerView = [UIAlertController alertControllerWithTitle:@"委托界面B传过来的值" message:value preferredStyle:UIAlertControllerStyleAlert];
//给警告框添加按钮 UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }];
[alerView addAction:action]; //弹出警告框
[self presentViewController:alerView animated:YES completion:nil ];
}
- (IBAction)segueBtn:(id)sender {}/** * 跳转到B的时候调用 * 作用:设置A为B的代理 */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
//设置跳转时的目标控制器
ViewControllerB *vc = segue.destinationViewController; //设置A为B的代理
vc.delegate = self;
}
@end
最终效果代理逆传值演示.gif