最近項(xiàng)目中要用到AlertView ,但是alertView只能在代理中調(diào)用,于是給它填加了一個(gè)Block支持。
首先我們來創(chuàng)建一個(gè)AlertView的分類叫做 UIAlertView (Block)
定義一個(gè)點(diǎn)擊彈出按鈕后的回調(diào)block
typedef void(^CompleteBlock) (ButtonIndex);
在h文件中定義一個(gè)方法:
- (void)alertViewWithBlock:(CompleteBlock) block;
然后我們在m文件中實(shí)現(xiàn)這個(gè)方法:
static char key;
- (void)showAlertViewWithCompleteBlock:(CompleteBlock)block { //首先判斷這個(gè)block是否存在 if(block) { //這里用到了runtime中綁定對(duì)象,將這個(gè)block對(duì)象綁定alertview上 objc_setAssociatedObject(self, &key,block,OBJC_ASSOCIATION_COPY); //設(shè)置delegate self.delegate=self; } //彈出提示框 [self show]; }
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)btnIndex { //拿到之前綁定的block對(duì)象 CompleteBlock block =objc_getAssociatedObject(self, &key); //移除所有關(guān)聯(lián) objc_removeAssociatedObjects(self); if(block) { //調(diào)用block 傳入此時(shí)點(diǎn)擊的按鈕index block(buttonIndex); } }
下面給出一個(gè)實(shí)際調(diào)用的例子
UIAlertView*alertView = [[UIAlertViewalloc]initWithTitle:@"檢測到有新的菜單功能包,是否更新"message:@"提示:不更新將無法進(jìn)入"delegate:nilcancelButtonTitle:@"取消"otherButtonTitles:@"確認(rèn)",nil];
__typeof(self)__weak weakSelf =self;
[alertViewshowAlertViewWithCompleteBlock:^(NSIntegerbuttonIndex) {
if(buttonIndex != alertView.cancelButtonIndex) {
//do something
}
}];