Block 傳值的概念類似於 C 語言中的函數指標。在 ViewController 之間傳遞資料時非常方便。本文延續先前的例子,示範如何把資料從 Second 頁傳回 First 頁——用 Block 來完成,看起來和協議(delegate)很像,但寫法更簡潔。
- (void)viewDidLoad
{
[super viewDidLoad];
self.nameLable = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 60)]autorelease];
self.nameLable.textAlignment = UITextAlignmentCenter;
self.nameLable.font = [UIFont systemFontOfSize:50];
self.nameLable.textColor = [UIColor blueColor];
[self.view addSubview:self.nameLable];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(130, 170, 60, 40);
[button setTitle:@"下一個" forState:UIControlStateNormal];
[button addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)pushNext:(id)sender
{
//初始化 second
SecondViewController *second = [[SecondViewController alloc]init];
///呼叫 block,把回調邏輯傳過去
second.send = ^(NSString *str){
self.nameLable.text = str;
};
//推過去
[self.navigationController pushViewController:second animated:YES];
[second release];
}
#import <UIKit/UIKit.h> typedef void (^SendMessage) (NSString *str); ///宣告 block 類型 @interface SecondViewController : UIViewController<UITextFieldDelegate> @property (nonatomic, copy) SendMessage send; //宣告一個 block 類型屬性 @end
- (void)viewDidLoad
{
[super viewDidLoad];
UITextField *textFd = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 300, 150)];
textFd.borderStyle = UITextBorderStyleRoundedRect;
textFd.delegate = self;
textFd.tag = 100;
[self.view addSubview:textFd];
[textFd release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
//先判斷,再呼叫 block 傳遞實參
if (self.send) {
self.send (textField.text);
}
return YES;
}
透過在 First 頁設定 send 這個 block、在 Second 頁觸發它,就能把輸入的文字即時回傳到上一頁,比 delegate 少寫了不少樣板程式碼。