标签:
AViewController.h
@interface AViewController : UIViewController {
UILabel *valueLabel;//?来接收SecondViewController传回的值
}
@end
实现AViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
[self.view addSubview:valueLabel];
UIBarButtonItem *nextBtn = [[UIBarButtonItem alloc] initWithTitle:@"next"
style:UIBarButtonItemStylePlain target:self action:@selector(nextClick)];
self.navigationItem.rightBarButtonItem = nextBtn;
}
- (void)nextClick
{
BViewController *svc = [[BViewController alloc] init];
svc.backValue = ^(NSString *strValue) {//设置SecondViewController?边的block属性,
这是本程序的关键
valueLabel.text = strValue;
};
[self.navigationController pushViewController:svc animated:YES];
}
BViewController.h
@interface BViewController : UIViewController
@property (nonatomic, copy) void (^backValue)(NSString *strValue);
@property (nonatomic, retain) UITextField *text;
@end
实现BViewController.m
@implementation BViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
text = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 300, 40)];
text.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:text];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10, 110, 60, 30);
[btn setTitle:@"返回" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (void)btnClick
{
self.backValue(self.text.text);//调?block?法
[self.navigationController popViewControllerAnimated:YES];
}
@end
block传值的思路:
1,A类要传值,即建立block属性 void (^backValue)(NSString *strValue);然后实现它:self.backValue(要传的值)
2,B类要得到A的传值 即实现A的的属性。
AViewController *aVC = [[AViewController alloc] init];
//通过block传值,城市切换
aVC.backValue = ^(NSString *strValue) {//设置SecondViewController?边的block属性,这是本程序的关键
self.cityName = strValue;
};
3,分析blcok属性的写法
返回值-名称-参数
返回值-名称-等号
@property (nonatomic, copy) void (^backValue) (NSString *strValue); @property (nonatomic, copy) NSString *name; =
标签:
原文地址:http://my.oschina.net/u/2346786/blog/490178