開發IOS時經常會使用到UIAlertView類,該類提供了一種標準視圖,可向用戶展示警告信息。當用戶按下按鈕關閉該視圖時,需要用委托協議(Delegate PRotocol)來處理此動作,但是要設置好這個委托協議,就得把創建警告視圖和處理按鈕動作的代碼分開。
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];
}
}
假如想在一個類中處理多個UIAlertView,那么代碼會更加復雜,需要在delegate方法中加入對AlertView的tag的判斷。
如果能在創建UIAlertView時把處理每個按鈕的邏輯寫好,那就簡單多了,我們可以使用BLOCK來完成。
一、使用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/
新聞熱點
疑難解答