如何执行UIAlertAction的处理程序? [英] How can I perform the handler of a UIAlertAction?
问题描述
我正在尝试编写一个帮助程序类,以允许我们的应用程序同时支持UIAlertAction
和UIAlertView
.但是,当为UIAlertViewDelegate
编写alertView:clickedButtonAtIndex:
方法时,遇到了以下问题:我看不到在UIAlertAction
的处理程序块中执行代码的方法.
I'm trying to write a helper class to allow our app to support both UIAlertAction
and UIAlertView
. However, when writing the alertView:clickedButtonAtIndex:
method for the UIAlertViewDelegate
, I came across this issue: I see no way to execute the code in the handler block of a UIAlertAction
.
我正在尝试通过在名为handlers
I'm trying to do this by keeping an array of UIAlertAction
s in a property called handlers
@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
标头只有:
However, there is no action.handler
property, or indeed any way I can see to fetch that, since the UIAlertAction
header just has:
NS_CLASS_AVAILABLE_IOS(8_0) @interface UIAlertAction : NSObject <NSCopying>
+ (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
块中的代码吗?
Is there some other way to execute the code in the handler
block of a UIAlertAction
?
推荐答案
经过一番实验,我才弄清楚了这一点.事实证明,可以将处理程序块转换为函数指针,并且可以执行该函数指针.
After some experimentation I just figured this out. Turns out that the handler block can be cast as a function pointer, and the function pointer can be executed.
像这样
//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);
这篇关于如何执行UIAlertAction的处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!