//关于block传值类似与代理传值,而block的优点就是不用繁琐的定义委托代理,下面是我写得一个小demo,献给学习block新手<img alt="微笑" src="http://static.blog.youkuaiyun.com/xheditor/xheditor_emot/default/smile.gif" />,一起学习讨论哈,望大神们不吝赐教
<pre name="code" class="objc">#import <UIKit/UIKit.h>
#import "PushViewController.h"
@interface RootViewController : UIViewController
@property(nonatomic,retain)UITextField * textfield;
/**
* 设置控制器的属性来传值
*/
@property(nonatomic,retain)PushViewController * push;
@end
#import "RootViewController.h"
#import "PushViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title =@"RootViewController.h";
/**
* 创建接收控件
*/
UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 200, 220, 40)];
self.textfield =textField;
textField.backgroundColor = [UIColor redColor];
[self.view addSubview:textField];
//push按钮
UIButton * push = [UIButton buttonWithType:UIButtonTypeCustom];
push.frame = CGRectMake(100, 300, 120, 50);
[push setTitle:@"push" forState:UIControlStateNormal];
[push addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];
push.backgroundColor = [UIColor greenColor];
[self.view addSubview:push];
_push = [[PushViewController alloc]init];
__block UITextField * text = self.textfield;
/**
* 实现要把值传给的控件
*/
_push.traditionalBlock = ^(NSString * string){
text.text = string;
};
}
//push事件
-(void)push:(UIButton *)sender
{
[self.navigationController pushViewController:_push animated:YES];
}
@end
#import <UIKit/UIKit.h>
/**
* 定义block
*/
typedef void(^TraditionalBlock)(NSString *);
@interface PushViewController : UIViewController
@property(nonatomic,retain)UITextField * textfield;
/**
* 声明一个block属性
*/
@property(nonatomic,copy)TraditionalBlock traditionalBlock ;
#import "PushViewController.h"
@interface PushViewController ()
@end
@implementation PushViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title =@"PushViewController.h";
//创建一个控件来接受值
UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 200, 220, 40)];
self.textfield =textField;
textField.backgroundColor = [UIColor orangeColor];
[self.view addSubview:textField];
//pop按钮
UIButton * pop = [UIButton buttonWithType:UIButtonTypeCustom];
pop.frame = CGRectMake(100, 300, 120, 50);
[pop addTarget:self action:@selector(pop:) forControlEvents:UIControlEventTouchUpInside];
[pop setTitle:@"传值" forState:UIControlStateNormal];
pop.backgroundColor = [UIColor greenColor];
[self.view addSubview:pop];
}
/**
* pop事件
*/
-(void)pop:(UIButton *)sender
{
/**
* 实现block方法以及自己要传得值
*/
_traditionalBlock(_textfield.text);
[self.navigationController popViewControllerAnimated:YES];
}