首先要意识到,block的本质,block本身就是一个函数。
所以,block传值就是利用block的声明,定义,调用这三个步骤即可以实现。
第一步:声明,需要我们在要传值的界面声明一个block的功能,也包括要传递的参数的类型。
第二步:定义,需要我们在要接收值的界面定义block的具体实现细节,比如说,把传递过来的形参赋给谁。
第三步:调用,需要我们在要传值的界面调用block,把实参传递出去。
第二个界面的代码片段:
//1.取别名
typedef void(^PassValueBlock)(NSString *text);
@interface CustomViewController : UIViewController
//2.写成属性,因为外界要访问
@property(nonatomic,strong) PassValueBlock passValueBlock;
@end
============================================
#import "CustomViewController.h"
@interface CustomViewController ()<UITextFieldDelegate>
@property(nonatomic,strong) UITextField *textField;
@end
@implementation CustomViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 200, 40)];
_textField.borderStyle = UITextBorderStyleRoundedRect;
_textField.placeholder = @"输入点什么";
[self.view addSubview:_textField];
_textField.delegate = self;
self.navigationItem.title = @"第二页";
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//使用部分
self.passValueBlock(_textField.text);
//返回上一个
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
===================================================第一个界面需要接收值:
#import "RootViewController.h"
#define kScreenWith [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
@interface RootViewController ()
@property(nonatomic,strong) UILabel *label;
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 40)];
_label.backgroundColor = [UIColor whiteColor];
_label.textColor = [UIColor redColor];
_label.text = @"你想说什么";
[self.view addSubview:_label];
self.navigationItem.title = @"第一页";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editAction:)];
}
-(void)editAction:(id)sender
{
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CustomViewController *customVC = [[CustomViewController alloc]init];
//展开部分--实现
customVC.passValueBlock = ^(NSString *text)
{
_label.text = text;
};
[self showDetailViewController:customVC sender:nil] ;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end