iOS.UI進階Block的使用,ios.uiblock

來源:互聯網
上載者:User

iOS.UI進階Block的使用,ios.uiblock

最簡單的block使用
  使用block的三個步驟:1.定義block變數 2.建立block代碼塊 3.調用block匿名函數

  定義一個block的構成包括:傳回值,block名,參數類型。

  block代碼塊作為一個匿名函數是可以被寫在其他方法中的,所以一般我們將block代碼塊寫在其他方法裡,調用該方法的時候block代碼塊將不會被執行,只有回調block代碼塊的時候,才會執行。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(nonatomic,copy) void(^myBlock)(int);//1.聲明一個block變數,直接將block聲明成一個屬性變數更方便實用。

@end

ViewController.m

#import "ViewController.h"

#import "NewViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

 //注意:先載入寫block代碼塊的方法

    [self blockTest];

 }

-(void)blockTest{

    //2.在方法裡面寫block代碼塊

    _myBlock = ^(int a){

        NSLog(@"%d",a);

    };

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    //3.調用block匿名函數

    _myBlock (10);

    NewViewController * newViewController = [[NewViewController alloc]init];

    newViewController.block = _myBlock;

    [self presentViewController:newViewController animated:YES completion:^{

     }];

}

@end

   上面代碼,在ViewController裡面實現了block實現的三個步驟,該block的功能就是列印參數值。

  

  touch方法實現從ViewController到NewViewController的跳轉,同時將ViewController裡面的block即myBlock賦給NewViewController裡定義的block,使得兩個block實質上成為同一個block,這樣,在NewViewController裡面就耶可以調用ViewController裡的代碼塊了。

NewViewController.h

#import <UIKit/UIKit.h>

#import "ViewController.h"

@interface NewViewController : UIViewController

@property(nonatomic,copy)void(^block)(int a);

@end

NewViewController.m

#import "NewViewController.h"

@interface NewViewController ()

@end

@implementation NewViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor=[UIColor grayColor];

 }

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    self.block(100);

    [self dismissViewControllerAnimated:YES completion:^{

    }];

}

@end

 

初學iOS,如有錯誤,請不吝賜教!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.