標籤:
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; =
iOS block使用