iOS开发——block传值
要实现界面之间值得传递,有两种方法,一种是利用代理传值,另一种是利用block传值。
Apple 官方文档中是这样介绍block的,A block is an anonymous inline collection of code,and sometimes also called a “closure”.block是个代码块,但可以将他当做一个对象处理。下面就举个利用block实现界面间的传值。
本例说明:(firstView 的lablel文本初始值是first,当点击按钮进行页面跳转之后进入secondView的时候,此时block改变firstView中label的文本值为second)
firstView.m
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
//创建一个Label,用于观察block调用前后label.text的变化
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
label.text = @"first";
self.label = label;
[self.view addSubview:self.label];
//创建一个button实现界面间的跳转
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(50, 150, 150, 100);
[button setTitle:@"To secondView" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
-(void)buttonPressed
{
SecondViewController *secondView = [[SecondViewController alloc] init];
//block声明的同时赋值
secondView.myBlock = ^(NSString *color){
self.label.text = color;
};
//跳转到secondView的实现方法
[self presentViewController:secondView animated:YES completion:nil];
}
secondView.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
//block属性
@property(nonatomic,strong)void(^myBlock)(NSString *color);
@end
secondView.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor greenColor];
//创建一个按钮,用于返回firstView
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(50, 150, 150, 100);
[button setTitle:@"cancle" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
//调用myBlock,传入second参数
self.myBlock(@"second");
}
-(void)buttonPressed
{
//返回之前的控制器
[self dismissViewControllerAnimated:YES completion:nil];
}
运行代码,结果如下:
开始的firstView界面
点击按钮后跳转到secondView
点击按钮返回firstView,可看到label文本从first改变成了second