1.继承UIButton ;
2.在自己定义的button类中的方法
addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 实现block的触发
代码示例:
// ZJBlockButton.h
// BlockTest
//
// Created by 何助金 on 15/4/5.
// Copyright (c) 2015年 何助金. All rights reserved.
//
#import <UIKit/UIKit.h>
@classZJBlockButton;
typedef void (^ButtonBlock)(ZJBlockButton *);//定义一个block
@interface ZJBlockButton : UIButton
@property (nonatomic,copy)ButtonBlock block;
@end
// ZJBlockButton.m
// BlockTest
//
// Created by 何助金 on 15/4/5.
// Copyright (c) 2015年 何助金. All rights reserved.
//
#import "ZJBlockButton.h"
@implementation ZJBlockButton
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[selfaddTarget:selfaction:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
}
returnself;
}
- (void)buttonClick:(ZJBlockButton *)sender
{
_block(self);
}
3.使用:
ZJBlockButton *zjButton = [[ZJBlockButton alloc]initWithFrame:CGRectMake(100, 300, 90, 90)];
zjButton.block = ^(ZJBlockButton *button){
NSLog(@"button click!");
};
[zjButton setTitle:@"touchButton"forState:UIControlStateNormal];
zjButton.backgroundColor = [UIColor grayColor];
[self.view addSubview:zjButton];
PS:可以用同样的方法实现 alertView的Block
// ZJAlertView.h
// BlockTest
//
// Created by 何助金 on 15/4/5.
// Copyright (c) 2015年 何助金. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void (^AlertBlock)(NSInteger);//定义block类型
@interface ZJAlertView : UIAlertView
@property (nonatomic,copy)AlertBlock block;
//需要自定义初始化方法 添加参数 block:(AlertBlock)block;
-(instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles block:(AlertBlock)block;
@end
的方法实现 alertView的block响应 直接上代码
// ZJAlertView.m
// BlockTest
//
// Created by 何助金 on 15/4/5.
// Copyright (c) 2015年 何助金. All rights reserved.
//
#import "ZJAlertView.h"
@implementation ZJAlertView
-(instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles block:(AlertBlock)block
{
self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles,nil];
if (self) {
self.block = block ;//block 绑定
}
returnself;
}
//#pragma mark -AlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//这里调用函数指针_block(要传进来的参数);
_block(buttonIndex);
}
应用:
- (void)creatBlockAlertView
{
ZJAlertView *alertView = [[ZJAlertViewalloc]initWithTitle:@"test"message:@"alert Block "delegate:nilcancelButtonTitle:@"cancel"otherButtonTitles:@"Ok"block:^(NSInteger index) {
NSLog(@"click at index %ld",index);
}];
[alertView show];
}