我正在尝试编写一个帮助程序类,让我们的应用程序支持 UIAlertAction
和 UIAlertView
。但是,在为 UIAlertViewDelegate
编写 alertView:clickedButtonAtIndex:
方法时,我遇到了这个问题:I see no way to execute the code in the handler block of一个 UIAlertAction
。
我试图通过在名为 handlers
的属性中保留一组 UIAlertAction
来实现这一点
@property (nonatomic, strong) NSArray *handlers;
然后像这样实现一个委托(delegate):
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIAlertAction *action = self.handlers[buttonIndex];
if (action.enabled)
action.handler(action);
}
但是,没有 action.handler
属性,或者实际上我可以看到获取它的任何方式,因为 UIAlertAction
header 只有:
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
block 中的代码?
最佳答案
经过一些实验,我才明白这一点。事实证明,处理程序 block 可以转换为函数指针,并且可以执行函数指针。
像这样
//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);
关于ios - 如何执行 UIAlertAction 的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29773960/