iOS块传值
塊傳值,塊類似于C中的函數指針。在Controller中傳遞數據非常方便,還是繼續上一章的例子,將數據從Second傳遞到First,這里使用塊來完成,看起來似乎和協議很像,不過比協議略簡單。
代碼如下所示:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /// FirstViewController - (void)viewDidLoad { ????[super viewDidLoad]; ???? ????self.nameLable = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 60)]autorelease]; ????self.nameLable.textAlignment = UITextAlignmentCenter; ????self.nameLable.font = [UIFont systemFontOfSize:50]; ????self.nameLable.textColor = [UIColor blueColor]; ????[self.view addSubview:self.nameLable]; ? ???? ????UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; ????button.frame = CGRectMake(130, 170, 60, 40); ????[button setTitle:@"下一個" forState:UIControlStateNormal]; ????[button addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside]; ????[self.view addSubview:button]; } ? - (void)pushNext:(id)sender { ????//初始化second ????SecondViewController *second = [[SecondViewController alloc]init]; ????///調用塊 ????second.send = ^(NSString *str){ ????????self.nameLable.text = str; ????}; ????//推過去 ????[self.navigationController pushViewController:second animated:YES]; ????[second release]; } |
Objective-C
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | / SecondViewController.h #import <UIKit/UIKit.h> typedef??void (^SendMessage) (NSString *str); ///聲明塊 ? @interface SecondViewController : UIViewController<UITextFieldDelegate> @property (nonatomic, copy) SendMessage send;??//聲明一個塊類型屬性 @end ? /SecondViewController.m - (void)viewDidLoad { ????[super viewDidLoad]; ???? ????UITextField *textFd = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 300, 150)]; ????textFd.borderStyle = UITextBorderStyleRoundedRect; ????textFd.delegate = self; ????textFd.tag = 100; ????[self.view addSubview:textFd]; ????[textFd release]; } ? - (BOOL)textFieldShouldReturn:(UITextField *)textField { ????[textField resignFirstResponder]; ????//先判斷,在調用塊傳遞實參 ????if (self.send) { ????????self.send (textField.text); ????} ????return YES; } |
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: iOS中XML解析汇总
- 下一篇: QQ红包风车图案怎么画 风车图案画法详解