协议传值,反向传值,将值从第二个界面传回第一个界面。
协议传值的六步:
- 声明协议,自定义声明一个协议方法
- 声明代理人属性
- 遵守协议
- 设置代理
- 实现协议方法
- 执行协议方法
代码:
//SecondViewController.h 文件中
#import <UIKit/UIKit.h>
//第1步
//声明协议
@protocol PassValueDelegate <NSObject>
//自定义协议方法
- (void)passContent:(NSString *)content;
@end
@interface SecondViewController : UIViewController
@property UITextField *textfield;
//第2步
//声明代理人属性
@property id<PassValueDelegate> delegate;
@end
//FirstViewController.m文件中
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
//第3步 签订协议
<PassValueDelegate>
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
_btn.frame = CGRectMake(140, 210, 100, 40);
[_btn setTitle:@"下一页" forState:UIControlStateNormal];
[_btn addTarget:self action:@selector(pressNext) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_btn];
_content = [[UILabel alloc] initWithFrame:CGRectMake(140, 160, 200, 40)];
_content.backgroundColor = [UIColor grayColor];
[self.view addSubview:_content];
}
- (void)pressNext {
SecondViewController *secondView = [[SecondViewController alloc] init];
//第四步 设置代理
secondView.delegate = self;
[self presentViewController:secondView animated:YES completion:nil];
}
//第五步 实现协议方法
- (void)passContent:(NSString *)content {
_content.text = content;
}
//在SecondViewController.m 文件中
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
_textfield = [[UITextField alloc] initWithFrame:CGRectMake(50, 130, 300, 40)];
_textfield.borderStyle = UITextBorderStyleLine;
[self.view addSubview:_textfield];
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
backBtn.frame = CGRectMake(100, 210, 100, 40);
[backBtn setTitle:@"返回" forState:UIControlStateNormal];
[backBtn addTarget:self action:@selector(pressBack) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:backBtn];
}
- (void)pressBack {
//第6步 执行协议方法
[self.delegate passContent:_textfield.text];
[self dismissViewControllerAnimated:YES completion:nil];
}
效果图:
第一个界面,如图
点击下一页,切换到第二个界面,在第二个界面的文本框输入内容,如图
点击返回,第一个界面显示如下: