标签:
说明:本文是在了解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> //定义一个block typedef 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
标签:
原文地址:http://www.cnblogs.com/Roki/p/4558629.html