iOS塊傳值

來源:互聯網
上載者:User

塊傳值,塊類似於C中的函數指標。在Controller中傳遞資料非常方便,還是繼續上一章的例子,將資料從Second傳遞到First,這裡使用塊來完成,看起來似乎和協議很像,不過比協議略簡單。 代碼如下所示:    /////////// ////////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; }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.