使用block传值一般都是后面控制器往前面控制器传值时使用
前页面
#import "ViewController.h"
#import "SecondController.h" // 后面页面
@interface ViewController ()
@property (nonatomic, strong)UILabel *labels;
@property (nonatomic, strong)UIButton *buttons;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addViews];
}
- (void)addViews {
self.labels = [[UILabel alloc]init];
self.labels.backgroundColor = [UIColor redColor];
self.labels.frame = CGRectMake(100, 100, 200, 40);
[self.view addSubview:self.labels];
self.buttons = [UIButton buttonWithType:UIButtonTypeCustom];
self.buttons.frame = CGRectMake(100, 200, 50, 30);
self.buttons.backgroundColor = [UIColor blackColor];
[self.buttons addTarget:self action:@selector(actionss) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.buttons];
}
- (void)actionss
{
// 跳转到后面页面 当返回时会携带参数过来
SecondController *second = [[SecondController alloc]init];
// block 传值
[second returnText:^(NSString *showText) {
self.labels.text = showText;
}];
[self presentViewController:second animated:YES completion:nil];
}
@end
*后面页面(和面页面会往前页面传值)*
*.h页面代码*
typedef void(^ReturnTextBlock)(NSString *showText);
@interface SecondController : UIViewController
@property (nonatomic, copy)ReturnTextBlock returnTextBlock;
- (void)returnText:(ReturnTextBlock)block;
*.m页面代码*
#import "SecondController.h"
@interface SecondController ()
@property (nonatomic, strong)UIButton *backB;
@property (nonatomic, strong)UITextField *textFields;
@end
@implementation SecondController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self addBlock];
}
- (void)addBlock {
self.backB = [UIButton buttonWithType:UIButtonTypeCustom];
self.backB.backgroundColor = [UIColor purpleColor];
self.backB.frame = CGRectMake(100, 100, 50, 30);
[self.backB addTarget:self action:@selector(actionss) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.backB];
self.textFields = [[UITextField alloc]init];
self.textFields.backgroundColor = [UIColor grayColor];
self.textFields.frame = CGRectMake(30, 30, (self.view.frame.size.width - 30) / 2, 30);
[self.view addSubview:self.textFields];
}
- (void)actionss
{
[self dismissViewControllerAnimated:YES completion:nil];
NSLog(@"SecondController--- %@", self.textFields.text);
}
- (void)returnText:(ReturnTextBlock)block
{
self.returnTextBlock = block;
}
- (void)viewWillDisappear:(BOOL)animated
{
if (self.returnTextBlock != nil) {
self.returnTextBlock(self.textFields.text);
}
}
@end
“`