block 传值
我们首先要考虑block在哪里定义 调用 和 实现; 如果A界面Push到B界面 我们从B界面传值到A界面
使用block的话我们一般是从后往前传值 , 还可以使用代理传值,但是代理传值的话又要创建代理,设置代理,实现代理的方法,操作起来比较麻烦 如果使用block传值的话 我们就可以简化很多;
从前往后传我们一般使用属性传值就可以了;
先说说我们要做的事情 我们在B界面建一个UITextFiled 在A界面建一个UILabel A界面push到B界面 我们要做的是将UITextField 里面的内容传给A界面中UILabel显示出来
1 B界面.h文件 2 #import <UIKit/UIKit.h> 3 4 5 typedef void(^BLOCK)(NSString * str); 6 7 @interface MyViewController : UIViewController 8 9 //定义block 10 @property(nonatomic,copy)BLOCK block; 11 12 //设置UITextfiled属性 13 @property(nonatomic,retain)UITextField * textfield; 14 15 @end 16 17 B界面.m文件 18 - (void)viewDidLoad { 19 [super viewDidLoad]; 20 self.view.backgroundColor=[UIColor whiteColor]; 21 22 //创建UITextfield 23 self.textfield=[[UITextField alloc]initWithFrame:CGRectMake(100, 100, 200, 30)]; 24 _textfield.borderStyle=UITextBorderStyleRoundedRect; 25 [self.view addSubview:_textfield]; 26 27 //创建返回上一个界面的button 28 UIButton * btn=[UIButton buttonWithType:UIButtonTypeSystem]; 29 btn.frame=CGRectMake(100, 200, 40, 40); 30 [btn setTitle:@"返回" forState:UIControlStateNormal]; 31 32 btn.backgroundColor=[UIColor yellowColor]; 33 [btn addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside]; 34 [self.view addSubview:btn]; 35 36 } 37 38 - (void)didClickButton:(UIButton *)btn 39 { 40 [self.navigationController popViewControllerAnimated:YES]; 41 42 //block调用 43 self.block(_textfield.text); 44 45 46 } 47 48 A界面.m文件 49 #import "ViewController.h" 50 #import "MyViewController.h" 51 @interface ViewController () 52 53 //创建UILabel来显示传过来的值 54 @property (strong, nonatomic) IBOutlet UILabel *UILabel; 55 @end 56 - (void)viewDidLoad { 57 [super viewDidLoad]; 58 59 //设置退出下一个界面的 UIBarButtonItem 60 UIBarButtonItem *rightBI=[[UIBarButtonItem alloc]initWithTitle:@"下一页" style:UIBarButtonItemStylePlain target:self action:@selector(didClickRightBI)]; 61 62 self.navigationItem.rightBarButtonItem=rightBI; 63 64 65 66 67 } 68 69 - (void)didClickRightBI 70 { 71 MyViewController * myVC=[[MyViewController alloc]init]; 72 73 [self.navigationController pushViewController:myVC animated:YES]; 74 75 76 //实现block的方法 77 myVC.block=^void(NSString *str) 78 { 79 80 81 _UILabel.text=str; 82 83 }; 84 85 86 }

浙公网安备 33010602011771号