最近项目中要用到AlertView ,但是alertView只能在代理中调用,于是给它填加了一个Block支持。
首先我们来创建一个AlertView的分类叫做 UIAlertView (Block)
定义一个点击弹出按钮后的回调block
typedef void(^CompleteBlock) (ButtonIndex);
在h文件中定义一个方法:
- (void)alertViewWithBlock:(CompleteBlock) block;
然后我们在m文件中实现这个方法:
static char key;
- (void)showAlertViewWithCompleteBlock:(CompleteBlock)block { //首先判断这个block是否存在 if(block) { //这里用到了runtime中绑定对象,将这个block对象绑定alertview上 objc_setAssociatedObject(self, &key,block,OBJC_ASSOCIATION_COPY); //设置delegate self.delegate=self; } //弹出提示框 [self show]; }
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)btnIndex { //拿到之前绑定的block对象 CompleteBlock block =objc_getAssociatedObject(self, &key); //移除所有关联 objc_removeAssociatedObjects(self); if(block) { //调用block 传入此时点击的按钮index block(buttonIndex); } }
下面给出一个实际调用的例子
UIAlertView*alertView = [[UIAlertViewalloc]initWithTitle:@"检测到有新的菜单功能包,是否更新"message:@"提示:不更新将无法进入"delegate:nilcancelButtonTitle:@"取消"otherButtonTitles:@"确认",nil];
__typeof(self)__weak weakSelf =self;
[alertViewshowAlertViewWithCompleteBlock:^(NSIntegerbuttonIndex) {
if(buttonIndex != alertView.cancelButtonIndex) {
//do something
}
}];
网友评论