1.子视图.h文件
#import <UIKit/UIKit.h>
//声明一个block
typedef void (^colorChangeBlock)(NSString *message, UIColor *color, NSError *error);
@interface ActionView : UIView
//改变父视图的背景,block作为参数
- (void)colorChange:(colorChangeBlock) bblock;
@end
2.子视图.m文件
#import "ActionView.h"
@implementation ActionView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor orangeColor];
}
return self;
}
- (void)colorChange:(colorChangeBlock) bblock
{
NSError *error;
NSString *message = @"老子是block";
UIColor *color = [UIColor grayColor];
//执行完成后,回调block,传入参数
bblock(message,color,error);
}
@end
3.控制器.h文件
#import <UIKit/UIKit.h>
@interface MainViewController : UIViewController
@end
4.控制器.m文件
#import "MainViewController.h"
#import "ActionView.h"
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SUBVIEW_HEIGHT 100
#define SUBVIEW_WIDTH 100
@interface MainViewController ()
@end
@implementation MainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
ActionView *actionView = [[ActionView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-SUBVIEW_WIDTH/2, SCREEN_HEIGHT/2-SUBVIEW_HEIGHT/2, SUBVIEW_WIDTH, SUBVIEW_HEIGHT)];
[actionView colorChange:^(NSString *message, UIColor *color, NSError *error) {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelay:1];
[UIView setAnimationDuration:2];
self.view.backgroundColor = color;
[UIView commitAnimations];
NSLog(@"message:%@",message);
}];
[self.view addSubview:actionView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end