Block支持的UIAlertView

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

开发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/

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航