由根视图传值到子视图可以使用在子视图上设置属性的方法.由子视图传值到根视图可以使用代理的方法实现
具体代码如下:
根视图控制器
#import "RootViewController.h"
#import "SecondViewController.h"
#warning 2-4接收协议
@interface RootViewController ()<SecondVCDelegate>
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor redColor];
self.navigationItem.title = @"首页";
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30, 80, 200, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField];
[textField release];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 150, 200, 30)];
label.text = @"11111";
[self.view addSubview:label];
[label release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(30, 200, 200, 30);
[button setTitle:@"进入到第二个界面" forState:UIControlStateNormal];
[button addTarget:self action:@selector(doTapButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
#pragma mark - 进入第二个界面
- (void)doTapButton:(UIButton *)button
{
SecondViewController *secondVC = [[SecondViewController alloc] init];
#warning 1-3给属性赋值。
UITextField *textFiled = self.view.subviews[0];
secondVC.str = textFiled.text;
#warning 2-3设置Delegate属性
secondVC.delegate = self;
[self.navigationController pushViewController:secondVC animated:YES];
[secondVC release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#warning 2-5实现协议中的方法
- (void)passTextFieldValue:(NSString *)text
{
//1.获取label
UILabel *label = self.view.subviews[1];
//2.给label赋值
label.text = text;
}
第二个视图控制器
#import "SecondViewController.h"
#import "RootViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
#warning 1-2 重写dealloc方法,释放属性对应的实例变量。
- (void)dealloc
{
[_str release];
[super dealloc];
}
#warning 2-6在特定的时间点让Delegate去调用协议中的方法
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if (_delegate && [_delegate respondsToSelector:@selector(passTextFieldValue:)]) {
[_delegate passTextFieldValue:((UITextField *)self.view.subviews[0]).text];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor orangeColor];
self.navigationItem.title = @"第二页";
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30, 80, 200, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField];
[textField release];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 150, 200, 30)];
#warning 1-4给需要值的地方提供值。
label.text = self.str;
[self.view addSubview:label];
[label release];
}