要實現界面之間值得傳遞,有兩種方法,一種是利用代理傳值,另一種是利用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