转自 http://blog.csdn.net/itpeng523/article/details/24315541
刚刚进入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) IBOutlet UIButton *btnOutlet;
- (IBAction)btnClick:(UIButton *)sender;
@end
#import "ViewController.h"
#import "ShowBtnColor.h"
@interface ViewController ()
@end
@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:tempblockcompletion:^(UIColor *colorEnum) {
/*函数回调 当block执行时就会回到这里*/
_btnOutlet.backgroundColor = colorEnum;
}];
}
@end
//
// 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
运行结果当点击按钮时