如何执行UIAlertAction的处理程序? [英] How can I perform the handler of a UIAlertAction?

查看:111
本文介绍了如何执行UIAlertAction的处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个帮助程序类,以允许我们的应用程序同时支持UIAlertActionUIAlertView.但是,当为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 UIAlertActions 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

还有其他方法可以执行UIAlertActionhandler块中的代码吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆