block傳值

來源:互聯網
上載者:User

標籤:android   style   color   檔案   for   io   

  定義block和定義delegate一樣,都是在得到需要的值那個頁面的類裡定義。

  eg:A類、B類,我要將A類中的值傳給B類,那麼我就到A類中定義block,B類取值就可以了。。。。

  

  For example:

第一步:

  A類中:

    .h檔案:

    #import "BaseViewController.h"

     //定義塊

typedef void (^addCommunity)(UIImage *img,NSString *title);

@interface MoreViewController : BaseViewController

@property(nonatomic,copy)addCommunity adds;

-(void)addCommunityWithBlock:(addCommunity)addBlock;

.m檔案:

- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view.

    imgView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

    NSString *img = @"market-android.png";

    imgView.image = [UIImage imageNamed:img];

    [self.view addSubview:imgView];

 

    lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(135, 230, 100, 30)];

    lblTitle.text = @"標題";

    lblTitle.textColor = [UIColor redColor];

    [self.view addSubview:lblTitle];

    

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 300, 100, 30)];

    [btn setTitle:@"添加" forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];

    [btn setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:btn];

}

-(void)add{

    _adds(imgView.image,lblTitle.text);  //block傳值

    

    [self.navigationController popToRootViewControllerAnimated:YES];

}

-(void)addCommunityWithBlock:(addCommunity)addBlock{

    _adds = addBlock;

}

第二步:

  B類中:

    .m檔案:

[more addCommunityWithBlock:^(UIImage *img,NSString *title){

                NSDictionary *dic = [NSDictionary dictionaryWithObject:img forKey:title];

            }];

在你需要用到值的地方,調用block,說明:more是A類的一個別名。這樣就把B頁面的值傳到了A頁面的NSDictionary中。。。。。。。我覺得寫得還算清楚吧!嘿嘿......

聯繫我們

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