协议传值是针对从后往前传值
先要自己定义协议 并且写协议方法 通过协议方法进行传值
@protocol SecondViewControllerDelegate <NSObject>
-(void)changeValue:(NSString *)value;
@end
@interface SecondViewController : UIViewController
@property(nonatomic,assign)id<SecondViewControllerDelegate>delegate;
@end
属性传值在.m文件中需要写的内容,控件的基本内容不再详述
@interface SecondViewController ()
@property(nonatomic,retain)UITextField *textField;
@property(nonatomic,retain)UIButton *button;
@end
@implementation SecondViewController
-(void)dealloc{
[_button release];
[_textField release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.textField];
self.view.backgroundColor = [UIColor lightGrayColor];
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
[self.button setTitle:@"返回" forState:UIControlStateNormal];
[self.view addSubview:self.button];
[self.button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)click:(UIButton *)button{
[self.navigationController popToRootViewControllerAnimated:YES];
[self.delegate changeValue:self.textField.text];
}
实现协议传值
#import "SecondViewController.h"
@interface MainViewController ()<SecondViewControllerDelegate>
@property(nonatomic,retain)UILabel *lable;
@property(nonatomic,retain)UIButton *button;
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 150, 40)];
[self.lable release];
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
[self.button setTitle:@"下一页" forState:UIControlStateNormal];
[self.button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
self.navigationController.navigationBar.translucent = NO;
}
-(void)click:(UIButton *)button{
SecondViewController *secVC = [[SecondViewController alloc]init];
[self.navigationController pushViewController:secVC animated:YES];
[secVC release];
secVC.delegate = self;
}
-(void)changeValue:(NSString *)value{
NSLog(@"%@",value);
self.lable.text = value;
}