反向传值可以用单例、代理和Block,当然SEL也可以,下面简单介绍一下Block传值,直接上代码
1.新建一个single view工程
2.在AppDelegate.m中
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
self.viewController.title = @"Block传值";
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = nc;
3.ViewController.h
@interface ViewController : UIViewController {
UILabel *valueLabel;//用来接收SecondViewController传回的值
}
@end
4.实现ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
[self.view addSubview:valueLabel];
[valueLabel release];
UIBarButtonItem *nextBtn = [[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextClick)];
self.navigationItem.rightBarButtonItem = nextBtn;
[nextBtn release];
}
- (void)nextClick
{
SecondViewController *svc = [[SecondViewController alloc] init];
svc.backValue = ^(NSString *strValue) {//设置SecondViewController里边的block属性,这是本程序的关键
valueLabel.text = strValue;
};
[self.navigationController pushViewController:svc animated:YES];
[svc release];
}
5.SecondViewController.h
@interface SecondViewController : UIViewController
@property (nonatomic, copy) void (^backValue)(NSString *strValue);
@property (nonatomic, retain) UITextField *text;
@end
6.实现SecondViewController.m
@implementation SecondViewController
@synthesize backValue;
@synthesize text;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
text = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 300, 40)];
text.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:text];
[text release];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10, 110, 60, 30);
[btn setTitle:@"返回" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (void)btnClick
{
self.backValue(self.text.text);//调用block方法
[self.navigationController popViewControllerAnimated:YES];
}
@end
效果图
返回之后: