開(kāi)發(fā)IOS時(shí)經(jīng)常會(huì)使用到UIAlertView類(lèi),該類(lèi)提供了一種標(biāo)準(zhǔn)視圖,可向用戶展示警告信息。當(dāng)用戶按下按鈕關(guān)閉該視圖時(shí),需要用委托協(xié)議(Delegate PRotocol)來(lái)處理此動(dòng)作,但是要設(shè)置好這個(gè)委托協(xié)議,就得把創(chuàng)建警告視圖和處理按鈕動(dòng)作的代碼分開(kāi)。
UIAlertView *inputAlertView = [[UIAlertView alloc] initWithTitle:@"Add a new to-do item:" message:nil delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"Add", nil];
//UIAlertViewDelegate protocol method
- (void)alertView:(UIAlertView *)alertView clickButtonAtButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
[self doCancel];
} else {
[self doContinue];
}
}
假如想在一個(gè)類(lèi)中處理多個(gè)UIAlertView,那么代碼會(huì)更加復(fù)雜,需要在delegate方法中加入對(duì)AlertView的tag的判斷。
如果能在創(chuàng)建UIAlertView時(shí)把處理每個(gè)按鈕的邏輯寫(xiě)好,那就簡(jiǎn)單多了,我們可以使用BLOCK來(lái)完成。
一、使用Category +Associate Object +Block
//UIAlertView+FHBlock.h
typedef void (^FHAlertViewCompletionBlock)(UIAlertView *alertView, NSInteger buttonIndex);
@interface UIAlertView (FHBlock) <UIAlertViewDelegate>
@property(nonatomic,copy) FHAlertViewCompletionBlock completionBlock;
@end
//UIAlertView+FHBlock.m
#import <objc/runtime.h>
@implementation UIAlertView (FHBlock)<UIAlertViewDelegate>
- (void)setCompletionBlock:(FHAlertViewCompletionBlock)completionBlock {
objc_setAssociatedObject(self, @selector(completionBlock), completionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
if (completionBlock == NULL) {
self.delegate = nil;
}
else {
self.delegate = self;
}
}
- (FHAlertViewCompletionBlock)completionBlock {
return objc_getAssociatedObject(self, @selector(completionBlock));
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickButtonAtButtonIndex:(NSInteger)buttonIndex {
if (self.completionBlock) {
self.completionBlock(self, buttonIndex);
}
}
@end
二、inheritance+Block
//FHAlertView.h
typedef void(^AlertBlock)(UIAlert* alert,NSInteger buttonIndex);
@interface FHAlertView:UIAlertView
@property(nonatomic,copy) AlertBlock completionBlock;
//FHAlertView.m
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickButtonAtButtonIndex:(NSInteger)buttonIndex {
if (self.completionBlock) {
self.completionBlock(self, buttonIndex);
}
}
@end
可以參考源碼:http://blog.projectrhinestone.org/preventhandler/
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注