block回調UIButton

//  BlockBtn.h


#import <UIKit/UIKit.h>


@interface BlockBtn : UIButton

@property (nonatomic,copy) void(^block)(void);

- (id)initWithFrame:(CGRect)frame;

- (void)clickAction;

@end


//  BlockBtn.m


#import "BlockBtn.h"


@implementation BlockBtn


- (id)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];

    if (self) {

        [self addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];

    }

    return self;

}


- (void)clickAction{

    _block();

}

@end


//  ViewController.m

#import "ViewController.h"

#import "BlockBtn.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];


    BlockBtn * bbtn = [[BlockBtn alloc] initWithFrame:CGRectMake((375-60)/2, 120, 60, 40)];

    bbtn.backgroundColor = [UIColor greenColor];

    bbtn.block = ^(void){

        NSLog(@"button event");

    };

    [self.view addSubview:bbtn];

    [bbtn release];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章