开发IOS时经常会使用到UIAlertView类,该类提供了一种标准视图,可向用户展示警告信息。当用户按下按钮关闭该视图时,需要用委托协议(DelegatePRotocol)来处理此动作,但是要设置好这个委托协议,就得把创建警告视图和处理按钮动作的代码分开。
UIAlertView*inputAlertView = [[UIAlertViewalloc] initWithTitle:@"Add a new to-do item:"message:nildelegate: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
typedefvoid (^FHAlertViewCompletionBlock)(UIAlertView *alertView,NSInteger buttonIndex);
@interface UIAlertView (FHBlock) <UIAlertViewDelegate>
@property(nonatomic,copy) FHAlertViewCompletionBlockcompletionBlock;
@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 {
returnobjc_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/