1. 程式人生 > >iOS非常重要的 block回撥

iOS非常重要的 block回撥

剛剛進入ios開發行業,發現開發中要用到大量的block回撥,由此可見它的重要性。學習它之前我也是網上找的資料,推薦這篇文章http://blog.csdn.net/mobanchengshuang/article/details/11751671,我也是從這裡得到一點啟發。如果對block的使用還不熟悉建議先看我的block那篇文章。下面我用自己的工程來解釋一下block回撥函式。

一、先建立一個簡單的xcode工程


ViewController.h檔案

//

//  ViewController.h

//  block回撥

//

//  Created by pengxun523 on 14-4-16.

//  Copyright (c) 2014

pengxun523. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutletUIButton *btnOutlet;

- (IBAction)btnClick:(UIButton *)sender;

@end

#import "ViewController.h"

#import "ShowBtnColor.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad

{

    [superviewDidLoad];

}

-(void)chargeMyIphone:(void(^)(void))finishBlock

{

}

- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (IBAction)btnClick:(UIButton *)sender

{

CGRect temp = CGRectMake(_btnOutlet.frame.origin.x, _btnOutlet.frame.origin.y, _btnOutlet.frame.size.width+50, _btnOutlet.frame.size.height+20);

    [ShowBtnColorChangeRootViewBtnRect:temp blockcompletion:^(UIColor *colorEnum) {

/*函式回撥 block執行時就會回到這裡*/

        _btnOutlet.backgroundColor = colorEnum;

    }];

}

@end

ShowBtnColor.h檔案

//

//  ShowBtnColor.h

//  block回撥

//

//  Created by pengxun523 on 14-4-22.

//  Copyright (c) 2014 pengxun523. All rights reserved.

//

#import <Foundation/Foundation.h>

typedef void (^Changcolor)(UIColor *colorEnum); //定義一個block返回值void引數為顏色值

@interface ShowBtnColor : NSObject

//回撥函式改變btn的顏色值

+ (void)ChangeRootViewBtnRect:(CGRect)rect blockcompletion:(Changcolor)Changcolorblock;

@end


//

//  ShowBtnColor.m

//  block回撥

//

//  Created by pengxun523 on 14-4-22.

//  Copyright (c) 2014 pengxun523. All rights reserved.

//

#import "ShowBtnColor.h"

@implementation ShowBtnColor

+ (void)ChangeRootViewBtnRect:(CGRect)rect blockcompletion:(Changcolor)Changcolorblock

{

    UIColor *temp = [UIColor greenColor];

    Changcolorblock(temp); //執行block 

}

@end

執行結果

 當點選按鈕時