
SecondViewController.h
#import <UIKit/UIKit.h>
1.声明一份协议.
@protocol SecondViewControllerDelegate <NSObject>
- (void)takeValue:(NSString *)strValue;
@end
@interface SecondViewController : UIViewController
2.声明代理人属性.
@property(nonatomic, assign)id<SecondViewControllerDelegate>delegate;
@end
SecondViewController.m
#import "SecondViewController.h"
#import "RootViewController.h"
@interface SecondViewController ()
@property(nonatomic, retain)UITextField *textField;
@end
@implementation SecondViewController
- (void)dealloc
{
[_textField release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 150, 50)];
self.textField.layer.borderWidth = 1;
self.textField.layer.cornerRadius = 10;
[self.view addSubview:self.textField];
[_textField release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(100, 200, 150, 50);
[button setTitle:@"返回" forState:UIControlStateNormal];
button.layer.borderWidth = 1;
button.layer.cornerRadius = 10;
[self.view addSubview:button];
[button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)backAction:(UIButton *)button {
[self.navigationController popViewControllerAnimated:YES];
3.设置代理人执行的协议方法
[self.delegate takeValue:self.textField.text];
}

RootViewController.m
#import "RootViewController.h"
#import "SecondViewController.h"
4.签订协议
@interface RootViewController ()<SecondViewControllerDelegate>
@property(nonatomic, retain)UITextField *myTextField;
@property(nonatomic, retain)UILabel *myLabel;
@end
@implementation RootViewController
- (void)dealloc
{
[_myTextField release];
[_myLabel release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 150, 50)];
self.myTextField.layer.borderWidth = 1;
self.myTextField.layer.cornerRadius = 10;
[self.view addSubview:self.myTextField];
[_myTextField release];
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 150, 50)];
self.myLabel.layer.borderWidth = 1;
self.myLabel.layer.cornerRadius = 10;
[self.view addSubview:self.myLabel];
[_myLabel release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(100, 300, 150, 50);
[button setTitle:@"下一页" forState:UIControlStateNormal];
button.layer.borderWidth = 1;
button.layer.cornerRadius = 10;
[self.view addSubview:button];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonAction:(UIButton *)button {
SecondViewController *secondVC = [[SecondViewController alloc] init];
[self.navigationController pushViewController:secondVC animated:YES];
[secondVC release];
5.设置代理人.
secondVC.delegate = self;
}
6.实现协议方法.
- (void)takeValue:(NSString *)strValue {
NSLog(@"%@", strValue);
self.myLabel.text = strValue;
}
