相比于属性传值,协议传值不仅可以向下一页传值,还能在任意界面传值,做到“向上传值”。
协议传值有以下几步:
1.在子视图.h文件中创建协议,写入属性
//SubViewController.h
//创建协议
@protocol SubViewControllerDelegate <NSObject>
-(void)changeValue:(NSString *)value;
@end
//写入属性
@interface SubdViewController : UIViewController
@property (nonatomic, assign) id<SecondViewControllerDelegate> delegate;
@property (nonatomic, strong) NSString *value;
@end
2.在子控制器.m文件中利用代理属性调用协议中的方法,进行传值
//SubViewController.m
#import "SubViewController.h"
//遵守协议
@interface SubViewController ()<UITextFieldDelegate>
@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, strong) UIButton *backBtn;
@end
@implementation SubViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
self.textField.center = self.view.center;
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.delegate = self;
self.textField.text = self.value;
[self.view addSubview:self.textField];
}
-(void)backAction:(id)sender
{
//存在代理人且有协议方法时才进行传值
if (self.delegate && [self.delegate respondsToSelector:@selector(changeValue:)]) {
//将自己的 textField.text 传给代理人
[self.delegate changeValue:self.textField.text];
}
}
3.在父控制器中遵守协议,设置代理,重写代理方法
//RootViewController.m
#import "RootViewController.h"
#import "SubViewController.h"
//遵守协议
@interface RootViewController ()<UITextFieldDelegate, SecondViewControllerDelegate>
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIButton *button;
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
self.label.center = self.view.center;
self.label.text = @"111";
self.label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:self.label];
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
[self.button setTitle:@"下一页" forState:UIControlStateNormal];
self.button.frame = CGRectMake(100, 100, 80, 30);
[self.button addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.button];
}
//重写代理方法
-(void)changeValue:(NSString *)value {
self.label.text = value;
}
-(void)nextAction:(id)sender {
SubViewController *sub = [[SubViewController alloc] init];
//设置代理
sub.delegate = self;
//利用协议传值
sub.value = self.label.text;
[self.navigationController pushViewController:sub animated:YES];
}