5

我正在尝试编写一个帮助程序类以允许我们的应用程序同时支持UIAlertActionUIAlertView. 但是alertView:clickedButtonAtIndex:.UIAlertViewDelegateUIAlertAction

我试图通过UIAlertAction在一个名为的属性中保留一个 s数组来做到这一点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标题只有:

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

是否有其他方法可以执行handlera 块中的代码UIAlertAction

4

2 回答 2

6

经过一些实验,我才明白这一点。原来,处理程序块可以转换为函数指针,并且可以执行函数指针。

像这样

//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);
于 2016-04-28T22:59:58.697 回答
2

包装类很棒,是吗?

.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插入 shelpers而不是UIAlertActions。

这样,您可以使所有属性都可以根据自己的意愿获取和设置,并且仍然保留原始类提供的功能。

于 2015-04-21T18:46:45.563 回答