实现方式就是自定义一个继承于UIButton或者UIAlert的类,然后添加一个block的属性。
重写UIButton的初始化方法,
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)onClick:(id)sender{
_block(self);
}
有block的alert,代码如下:
同样初始化init方法
- (id)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString*)otherButtonTitles block:(TouchBlock)block{
self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil];//注意这里初始化父类的
if (self) {
self.block = block;
}
return self;
}
//#pragma mark -AlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//这里调用函数指针_block(要传进来的参数);
_block(buttonIndex);
}
示例代码:
BlockButton *button = [[BlockButton alloc]initWithFrame:CGRectMake(100, 100, 40, 20)];
[button setBlock:^(BlockButton *button){
AlertBlock *alert = [[AlertBlock alloc]initWithTitle:@"提示" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex){
//在这里面执行触发的行为,省掉了代理,这样的好处是在使用多个Alert的时候可以明确定义各自触发的行为,不需要在代理方法里判断是哪个Alert了
if (buttonIndex == 0) {
NSLog(@"取消");
}else if (buttonIndex == 1){
NSLog(@"确定");
}
}];
[alert show];
}];