一、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