刚刚进入ios开发行业,发现开发中要用到大量的block回调,由此可见它的重要性。学习它之前我也是网上找的资料,推荐这篇文章http://blog.csdn.net/mobanchengshuang/article/details/11751671,我也是从这里得到一点启示。假设对block的使用还不熟悉建议先看我的block那篇文章。以下我用自己的project来解释一下block回调函数。
一、先创建一个简单的xcodeproject
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:temp blockcompletion:^(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
执行结果 当点击button时