赞
踩
block传值和协议传值类似,都是从下一界面往上一界面传值,两者之间在用法上也有着很多相似之处。
在第二个界面的.h文件里定义一个代码块,和一个block属性。
#import "ViewController.h" NS_ASSUME_NONNULL_BEGIN //定义一个代码块,传值参数可以为多个 typedef void(^block)(NSString *string); @interface SecondViewController : ViewController @property (nonatomic, strong) NSString *string; @property (nonatomic, strong) UIButton *button; //定义一个block属性 @property (nonatomic, copy) block newblock; @end NS_ASSUME_NONNULL_END
在第二个界面的.h文件里完成按钮的点击事件函数用于返回上一界面,在函数中给block传值:
- (void)pressback {
_newblock(_string);
[self dismissViewControllerAnimated:YES completion:nil];
}
在第一个界面往二个界面切换的时候,完成对第二个界面传的值进行赋值。
- (void)pressgo {
SecondViewController *viewcontroller = [[SecondViewController alloc] init];
viewcontroller.modalPresentationStyle = UIModalPresentationFullScreen;
[viewcontroller setNewblock:^(NSString *string) {
_label.text = string;
}];
[self presentViewController:viewcontroller animated:YES completion:nil];
}
视图一全部代码:
@implementation FirstViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. _label = [[UILabel alloc] initWithFrame:CGRectMake(200, 200, 100, 100)]; [self.view addSubview:_label]; self.view.backgroundColor = [UIColor orangeColor]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button addTarget:self action:@selector(pressgo) forControlEvents:UIControlEventTouchUpInside]; button.frame = CGRectMake(0, 0, 200, 200); [button setTitle:@"进入" forState:UIControlStateNormal]; [self.view addSubview:button]; } - (void)pressgo { SecondViewController *viewcontroller = [[SecondViewController alloc] init]; viewcontroller.modalPresentationStyle = UIModalPresentationFullScreen; [viewcontroller setNewblock:^(NSString *string) { _label.text = string; }]; [self presentViewController:viewcontroller animated:YES completion:nil]; }
视图二全部代码:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor systemPinkColor]; _button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [_button addTarget:self action:@selector(pressback) forControlEvents:UIControlEventTouchUpInside]; _button.frame = CGRectMake(0, 0, 200, 200); [_button setTitle:@"返回" forState:UIControlStateNormal]; [self.view addSubview:_button]; _string = [NSString stringWithFormat:@"iOS"]; } - (void)pressback { _newblock(_string); [self dismissViewControllerAnimated:YES completion:nil]; }
结果展示:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。