@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
BlockButton *btn = [[BlockButton alloc]initWithFrame:CGRectMake(50, 50, 100, 40)];
[btn setTitle:@"按钮" forState:UIControlStateNormal];
btn.backgroundColor = [UIColor purpleColor];
// btn.block = ^(BlockButton *btn){
// NSLog(@"打印");
// };
[self.view addSubview:btn];
btn.block = ^(BlockButton *btn)
{
BlockUIAlertView *alertView = [[BlockUIAlertView alloc]initWithTitle:@"提示" message:@"是否继续?" cancelButtonTitle:@"取消" otherButtonTitles:@"继续" buttonBlock:^(NSInteger index)
{
if (index == 0)
{
NSLog(@"取消");
}else if (index == 1){
NSLog(@"继续");
}
}];
[alertView show];
};
}
#import <UIKit/UIKit.h>
@class BlockButton;
typedef void(^TouchButton)(BlockButton *);
@interface BlockButton : UIButton
//Block 要用copy定义
@property (nonatomic,copy) TouchButton block;
@end
@implementation BlockButton
//复写初始化方法
-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
-(void)clickAction{
//两种方式调用
// self.block(self);
_block(self);
}
@end
#import <UIKit/UIKit.h>
typedef void(^ButtonBlock)(NSInteger);
@interface BlockUIAlertView : UIAlertView
@property (nonatomic,copy)ButtonBlock block;
- (instancetype)initWithTitle:(nullable NSString *)title
message:(nullable NSString *)message
cancelButtonTitle:(nullable NSString *)cancelButtonTitle
otherButtonTitles:(nullable NSString *)otherButtonTitles
buttonBlock:(nullable ButtonBlock)block;
@end
@implementation BlockUIAlertView
- (instancetype)initWithTitle:(nullable NSString *)title
message:(nullable NSString *)message
cancelButtonTitle:(nullable NSString *)cancelButtonTitle
otherButtonTitles:(nullable NSString *)otherButtonTitles
buttonBlock:(nullable ButtonBlock)block{
self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil];
if (self != nil) {
self.block = block;
}
return self;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
_block(buttonIndex);
}
@end