• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
麻麻的
博客园    首页    新随笔    联系   管理    订阅  订阅

Blcok代替委托方法,实现回调

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

posted on 2014-04-10 11:23  麻麻的  阅读(156)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3