剛剛進入ios開發行業,發現開發中要用到大量的block回調,因而可知它的重要性。學習它以前我也是網上找的資料,推薦這篇文章http://blog.csdn.net/mobanchengshuang/article/details/11751671,我也是從這裏獲得一點啓發。若是對block的使用還不熟悉建議先看個人block那篇文章。下面我用本身的工程來解釋一下block回調函數。ios
1、先建立一個簡單的xcode工程xcode
ViewController.h文件
函數
//學習
// ViewController.hatom
// block回調spa
//.net
// Created by pengxun523 on 14-4-16.code
// Copyright (c) 2014年 pengxun523. All rights reserved.orm
//blog
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *btnOutlet;
- (IBAction)btnClick:(UIButton *)sender;
#import "ViewController.h"
#import "ShowBtnColor.h"
@interface ViewController ()
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)chargeMyIphone:(void(^)(void))finishBlock
{
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// 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);
[ShowBtnColor ChangeRootViewBtnRect: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
運行結果
當點擊按鈕時