ios开发中传值方式一:block传值(支持逆向传值,不支持顺序传值!!!)
传值方式一:block传值 (仅支持逆向传值).
本例子是在firstViewController(firstVC)里面创建 UILabel * lab ,和 提交按钮. 在secondViewControlloer(secondVC) 里面 创建UITextField * textField; 和返回按钮.实现在secondVC界面的textField里面输入文字点击返回按钮之后在firstVC里面的lab上面显示textFied里面输入的文字.(我是在项目中直接拖得控件)
1,在secondViewController视图控制器的.h文件里面 完成block的定义和声明.
secondViewController.h
1 #import <UIKit/UIKit.h> 2 3 4 typedef void (^ReturnBlock)(NSString * text);//为声明的block定义一个名字ReturnBlock 5 6 @interface secondViewController : UIViewController 7 /* @property(weak,nonatomic)NSString * str;//这个没用 */ 8 9 @property(copy,nonatomic)ReturnBlock returnBlock;//定义一个block为secondVC的属性 10 11 -(void)backText:(ReturnBlock)block;//block执行的代码块 12 13 @end
2,在secondViewController里面实现方法
secondViewController.m
1 #import "secondViewController.h" 2 3 @interface secondViewController () 4 5 6 @property (weak, nonatomic) IBOutlet UITextField *textField; 7 @end 8 9 @implementation secondViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 // Do any additional setup after loading the view from its nib. 14 self.view.backgroundColor = [UIColor yellowColor]; 15 } 16 - (IBAction)btnClick:(id)sender { 17 [self.navigationController popToRootViewControllerAnimated:YES]; 18 } 19 //把传进来的代码块保存到本类的实例变量returnBlock中 20 -(void)backText:(ReturnBlock)block{ 21 self.returnBlock = block; 22 } 23 //在视图控制器将要消失的时候调用 24 -(void)viewWillDisappear:(BOOL)animated{ 25 if (_textField.text != nil) { 26 self.returnBlock(_textField.text); 27 } 28 }
3,在firstViewController里面的 按钮点击方法里面 实现 (这里有点疑问 为什么必须在第一个视图控制器里面的按钮方法里面实现??? 希望知道的可以跟我留言 谢谢!!)
firstViewController.m
1 #import "firstViewController.h" 2 #import "secondViewController.h" 3 4 @interface firstViewController () 5 @property (weak, nonatomic) IBOutlet UILabel *lab; 6 7 @end 8 9 @implementation firstViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 // Do any additional setup after loading the view from its nib. 14 self.view.backgroundColor= [UIColor greenColor]; 15 } 16 - (IBAction)btnClick:(id)sender { 17 secondViewController * secondVC = [[secondViewController alloc]init]; 18 [secondVC backText:^(NSString *text) { 19 _lab.text = text; 20 }]; 21 [self.navigationController pushViewController:secondVC animated:YES]; 22 23 }
这样就可以实现 block传值了! ^_^