使用Block的地方很多,其中传值只是其中的一小部分,下面介绍Block在两个界面之间的传值:
先说一下思想:
首先,创建两个视图控制器,在第一个视图控制器中创建一个UILabel和一个UIButton,其中UILabel是为了显示第二个视图控制器传过来的字符串,UIButton是为了push到第二个界面。
第二个界面的只有一个UITextField,是为了输入文字,当输入文字,并且返回第一个界面的时候,当第二个视图将要消失的时候,就将第二个界面上TextFiled中的文字传给第一个界面,并且显示在UILabel上。
第一页面
@interface ViewController ()
@property (nonatomic,strong)UILabel *label;
@property (nonatomic,strong)UIButton *btn;
@property (nonatomic,strong)FirstViewController *fir;
@end
@implementation ViewController
- (void)creatLabel{
self.label = [[UILabel alloc]init];
self.label.backgroundColor =[UIColor redColor];
self.label.frame =CGRectMake(10, 100, 100, 40);
[self.view addSubview:self.label];
}
- (void)creatBnt{
self.btn = [[UIButton alloc]init];
self.btn.backgroundColor =[UIColor brownColor];
self.btn.frame = CGRectMake(10, 200, 100, 40);
[self.view addSubview:self.btn];
[self.btn addTarget:self action:@selector(buttone:) forControlEvents:UIControlEventTouchUpInside];
[self.btn setTitle:@"跳转" forState:UIControlStateNormal];
}
- (void)buttone:(UIButton *)buttona{
// FirstViewController *first = [[FirstViewController alloc]init];
[self presentModalViewController:self.fir animated:YES];
NSLog(@"确定");
}
- (void)viewDidLoad {
self.fir = [[FirstViewController alloc]init];
[self.fir retunText:^(NSString *showText) {
self.label.text = showText;
}];
[self creatLabel];
[self creatBnt];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
第二页面.h:
#import <UIKit/UIKit.h>
//定义Block
typedef void (^ReturnTextBlock)(NSString *showText);
@interface FirstViewController : UIViewController
@property (nonatomic,strong) UITextField *field;
//定义Block属性
@property (nonatomic,copy) ReturnTextBlock returnTextBlock;
在第一个界面传进来一个Block语句块的函数,不用也可以,不过加上会减少代码的书写量
- (void)retunText:(ReturnTextBlock)block;
.m
#import "FirstViewController.h"
@interface FirstViewController ()
@property (nonatomic,strong) UIButton *btn1;
@end
@implementation FirstViewController
- (void)createField{
self.field = [[UITextField alloc]init];
// self.field.text = @"请输入";
self.field.backgroundColor =[UIColor redColor];
self.field.placeholder = @"请输入";
self.field.frame = CGRectMake(10, 100, 100, 40);
[self.view addSubview:self.field];
self.btn1 =[[UIButton alloc] initWithFrame:CGRectMake(10, 200, 100, 40)];
[self.btn1 addTarget:self action:@selector(button1:) forControlEvents:UIControlEventTouchUpInside];
[self.btn1 setTitle:@"返回" forState:UIControlStateNormal];
self.btn1.backgroundColor =[UIColor yellowColor];
[self.view addSubview:self.btn1];
}
- (void)button1:(UIButton *)btn{
[self dismissModalViewControllerAnimated:YES];
}
//Block实现
- (void)retunText:(ReturnTextBlock)block{
self.returnTextBlock = block;
}
- (void)viewWillDisappear:(BOOL)animated{
if (self.returnTextBlock != nil) {
self.returnTextBlock(self.field.text);
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor whiteColor];
[self createField];
// Do any additional setup after loading the view.
}