一、block延伸:页面间反向传值
1)first页面的代码
- (void)viewDidLoad {[super viewDidLoad];[self setupBtn];self.view.backgroundColor = [UIColor whiteColor];} - (void)setupBtn {UIButton * btn = [[UIButton alloc]init];[btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];btn.backgroundColor = [UIColor blackColor];btn.frame = CGRectMake(100, 100, 100, 100);[self.view addSubview:btn]; } - (void)buttonClick {SecondViewController * secondVC = [[SecondViewController alloc]init];//在first页面调用block输出字符串secondVC.myBlock= ^(NSString * str){NSLog(@"%@",str);};[self.navigationController pushViewController:secondVC animated:YES]; }
2)second页面的代码
//.h文件 #import <UIKit/UIKit.h>@interface SecondViewController : UIViewController //定义block @property (nonatomic,copy)void (^myBlock)(NSString * str); @end //.m文件 - (void)setupBtn {UIButton * btn = [[UIButton alloc]init];[btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];btn.backgroundColor = [UIColor blackColor];btn.frame = CGRectMake(100, 100, 100, 100);[self.view addSubview:btn]; } - (void)buttonClick {//通过block传值if (self.myBlock) {self.myBlock(@"haha");}[self.navigationController popToRootViewControllerAnimated:YES]; }
输出结果:
2016-02-19 11:36:55.168 03-block[983:70116] haha
参考博客:http://my.oschina.net/leejan97/blog/268536?fromerr=2UdIND3G