標籤:
說明:本文是在瞭解block基礎知識基礎上的應用,假定閱讀者已經具備block基礎知識。
目的:通過block回調方式將SecondViewController中的值傳入到ViewController中,在某些時候,通過block回調,可以避免delegate的繁瑣
1,建立Single View Application工程,建立SecondViewController
2,在ViewController中添加UILabel用於顯示SecondViewController傳過來的值,把label設定為成員變數,添加一個UIButton,用於點擊跳轉到SecondViewController
@interface ViewController (){ UILabel *_label;}@end- (void)viewDidLoad { [super viewDidLoad]; //添加UIButton,用於跳轉到SecondViewController UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 200, 300, 44)]; [btn setTitle:@"ToSecondViewController" forState:UIControlStateNormal]; btn.backgroundColor = [UIColor grayColor]; [btn addTarget:self action:@selector(toSecondViewController) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; //添加UILabel,用於顯示SecondViewController傳過來的值 _label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 300, 44)]; _label.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_label];}
3,在SecondViewController.m中添加一個UITextField,設定為成員變數,用於輸入值,添加一個UIButton,用於點擊跳回ViewController
@interface SecondViewController (){ UITextField *_textField;}@end- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; //添加一個按鈕用於返回ViewController UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 200, 300, 44)]; [btn setTitle:@"BackToViewController" forState:UIControlStateNormal]; btn.backgroundColor = [UIColor blueColor]; [btn addTarget:self action:@selector(backToViewController) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; //添加一個UITextField _textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 300, 44)]; _textField.backgroundColor = [UIColor greenColor]; [self.view addSubview:_textField];}
4,在SecondViewController.h中,利用typedef定義一個block,並設定成property,同時聲明一個回調方法
#import <UIKit/UIKit.h>//定義一個blocktypedef void (^ReturnValueBlock)(NSString *value);@interface SecondViewController : UIViewController@property (nonatomic,copy)ReturnValueBlock returnValueBlock;//回調方法- (void)returnValue:(ReturnValueBlock)block;@end
5,實現回調方法,並且在點擊返回ViewController按鈕時調用
- (void)backToViewController { //當點擊返回ViewController時回調 if (self.returnValueBlock != nil) { self.returnValueBlock(_textField.text); } [self dismissViewControllerAnimated:YES completion:nil];}- (void)returnValue:(ReturnValueBlock)block { self.returnValueBlock = block;}
6,在ViewController.m中使用block方法為label賦值
- (void)toSecondViewController { SecondViewController *second = [[SecondViewController alloc] init]; [second returnValue:^(NSString *value) { _label.text = value; }]; [self presentViewController:second animated:YES completion:nil];}
源碼地址:https://github.com/rokistar/PassValueUsingBlock
iOS block 回調