代理:又叫委托 自己不能去办得事,委托给别人去干
之前学过的UIAlertView UITextField都使用了代理
正向传值可以用属性
反向传值 代理Block
写代理的步骤(公式)
//需要帮忙的人( 请求帮带饭的人)
1.声明代理 里面的协议方法(@protocol)
2.声明协议的属性
3.什么时候需要 触发这个 代理方法
4.调用协议的属性 调用代理方法(委托)
//帮忙的人(帮忙带饭的人)
5.导入协议
6.在初始化有代理方法的 对象的地方 挂上代理(好心人答应帮忙带饭)
7.写上代理方法 等待被执行(帮买饭的动作)
步骤:
创建两个视图控制器ViewController和NextViewController
1、在NextViewController.h
//1.声明代理方法(不要在@interface里面声明代理方法)
@protocol NextDelegate <NSObject>
//@optional可选的
- (void)toLoginWithName:(NSString *)name;
/2.声明代理的属性(可以通过 这个属性 找到 代理方法)
@property(nonatomic,assign)id<NextDelegate>delegate;
//声明代理的属性 用assign分配到栈里面
//id 代理的类型<代理的名字>
2、NextViewController.m
初始化一个按钮(作用是 触发代理方法)
UIButton *rigetherButton = [UIButton buttonWithType:UIButtonTypeCustom];
rigetherButton.frame = CGRectMake(100, 100, 100, 35);
[rigetherButton setTitle:@"注册" forState:UIControlStateNormal];
rigetherButton.backgroundColor = [UIColor redColor];
[rigetherButton addTarget:self action:@selector(toRigether) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:rigetherButton];
3、什么时候需要 触发这个 代理方法
- (void)toRigether
{
//点击注册 注册成功的时候 触发代理方法
[self.navigationController popViewControllerAnimated:YES];
//4.调用协议的属性 调用代理方法(委托)这里把“葫芦娃”传过去
[self.delegate toLoginWithName:@"葫芦娃"];
}
4、在ViewController。m里面
//5导入协议(代理)
@interface ViewController ()<NextDelegate>
挂上代理(注意,在哪里初始化 代理的对象 就在哪里挂上代理)
//从第一个页面 传值 到第二个页面 (通过属性)
NextViewController *next = [[NextViewController alloc]init];
//6.挂上代理 在 初始化有代理方法的 对象的地方 挂上代理(好心人答应帮忙带饭)
next.delegate = self;
实现代理的方法(这里值已经传了过来,可以在方法里面输出来)
- (void)toLoginWithName:(NSString *)name
{
//7.写上代理方法 等待被执行(帮买饭的动作)
NSLog(@"%@:登陆成功",name);
}