如何执行UIAlertAction的处理程序?
我正在尝试编写一个帮助程序类,以允许我们的应用程序同时支持UIAlertAction
和UIAlertView
。 但是,在为UIAlertViewDelegate
编写alertView:clickedButtonAtIndex:
方法时,我遇到了这个问题: 我看不到在UIAlertAction
的处理程序块中执行代码的UIAlertAction
。
我试图通过在一个名为handlers
的属性中保留一组UIAlertAction
来做到这一点
@property (nonatomic, strong) NSArray *handlers;
然后实现这样的委托:
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { UIAlertAction *action = self.handlers[buttonIndex]; if (action.enabled) action.handler(action); }
但是,没有action.handler
属性,或者实际上我可以看到获取它的任何方式,因为UIAlertAction
头只有:
NS_CLASS_AVAILABLE_IOS(8_0) @interface UIAlertAction : NSObject + (instancetype)actionWithTitle:(NSString *)title style:(UIAlertActionStyle)style handler:(void (^)(UIAlertAction *action))handler; @property (nonatomic, readonly) NSString *title; @property (nonatomic, readonly) UIAlertActionStyle style; @property (nonatomic, getter=isEnabled) BOOL enabled; @end
是否有其他方法可以在UIAlertAction
的handler
块中执行代码?
经过一些实验,我才想到这一点。 事实certificate,处理程序块可以作为函数指针进行转换,并且可以执行函数指针。
像这样
//Get the UIAlertAction UIAlertAction *action = self.handlers[buttonIndex]; //Cast the handler block into a form that we can execute void (^someBlock)(id obj) = [action valueForKey:@"handler"]; //Execute the block someBlock(action);
包装类很棒,是吗?
在.h
:
@interface UIAlertActionWrapper : NSObject @property (nonatomic, strong) void (^handler)(UIAlertAction *); @property (nonatomic, strong) NSString *title; @property (nonatomic, assign) UIAlertActionStyle style; @property (nonatomic, assign) BOOL enabled; - (id) initWithTitle: (NSString *)title style: (UIAlertActionStyle)style handler: (void (^)(UIAlertAction *))handler; - (UIAlertAction *) toAlertAction; @end
在.m
:
- (UIAlertAction *) toAlertAction { UIAlertAction *action = [UIAlertAction actionWithTitle:self.title style:self.style handler:self.handler]; action.enabled = self.enabled; return action; }
…
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { UIAlertActionWrapper *action = self.helpers[buttonIndex]; if (action.enabled) action.handler(action.toAlertAction); }
您所要做的就是确保将UIAlertActionWrapper
插入到helpers
而不是UIAlertAction
。
这样,您可以使所有属性都可以根据您的内容获取和设置,并且仍然保留原始类提供的function。