以两个简单的界面举例 一个用来输入 一个用来展示输入的结果,总结的为反向传值,正向传值,不做赘述。
方法1.
协议方法实现反向传值
首先在SecondViewController.h文件里设置代理声明协议方法
#import <UIKit/UIKit.h>
//1.驱动方声明协议,约定执行的方法
@protocol ShowTextDelegate <NSObject>
//@optional,可选的协议方法
@required //代理方必须实现的方法
-(void)showText:(NSString *)text;
@optional //可选执行的协议方法
-(UIColor *)colorForShowText:(NSString *)text;
@end
@interface SecondViewController : UIViewController
//2.声明代理属性,委托所付出的代价
@property (nonatomic, weak) id <ShowTextDelegate> delegate;
@end
SecondViewController.m文件里
搭建简答的UI界面 设置界面跳转
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor cyanColor];
_textFiled = [[UITextField alloc]initWithFrame:CGRectMake(50, 200, self.view.frame.size.width - 100, 50)];
_textFiled.borderStyle = UITextBorderStyleRoundedRect;
_textFiled.adjustsFontSizeToFitWidth = YES;
_textFiled.minimumFontSize = 15;
_textFiled.font = [UIFont boldSystemFontOfSize:25];
[self.view addSubview:_textFiled];
}
//触摸结束时调用此方法
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//_textFiled 放弃第一响应
[_textFiled resignFirstResponder];
[_delegate showText:_textFiled.text];
//退出当前界面
[self dismissViewControllerAnimated:YES completion:nil];
}
在第一个界面展示输入的结果 ,要遵守代理 并实现协议方法
要引入第二界面的头文件,遵守协议 ,之后创建简单的UI 在按钮的点击时间里简历代理关系 之后实现协议方法
-(void)buttonClicked
{
//创建视图控制器
SecondViewController *svc = [[SecondViewController alloc]init];
//4.建立代理关系
svc.delegate = self;
// 设置跳转动画类型
svc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//跳转到第二视图控制器
[self presentViewController:svc animated:YES completion:nil];
}
//5.实现代理方法
-(void)showText:(NSString *)text
{
UILabel *label = (id)[self.view viewWithTag:10];
label.text = text;
}
//可选的协议方法,带返回值的
-(UIColor*)colorForShowText:(NSString *)text
{
UILabel *label = (id)[self.view viewWithTag:10];
label.text = text;
return [UIColor greenColor];
}
**
代理注意的点
*分清驱动方和代理方法<前提条件>
1.驱动方,声明协议,协议中约定方法
2.驱动方,声明delegate属性 <付出的代价>
3.代理方,遵循协议
4.建立代理关系
5.代理方,实现协议<协议中约定@required>方法,@optional选实现
6.驱动方,在合适的时间驱动代理执行协议方法
*/