如何编写一个通用函数来为UIAlertViewController创建UIAlertAction,以用于整个应用程序?

问题描述:

是否可以创建一个可以生成UIAlertAction并使用处理函数返回的函数。如何编写一个通用函数来为UIAlertViewController创建UIAlertAction,以用于整个应用程序?

我只是不想为UIAlertAction多次编写代码,只尝试创建一个可以为每个需要的场景创建UIAlertAction的函数。 这是我的代码。

UIAlertAction *actionPast = [self createActionButton:@"Past"]; 
    UIAlertAction *actionFuture = [self createActionButton:@"Future"]; 

    -(UIAlertAction *)createActionButton : (NSString *)title{ 
     UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}]; 
     return action; 
    } 

所以有没有任何可能性来恢复处理程序和单击任何UIAlertAction时执行任何任务。

+0

这个问题还不够清楚。你为什么要这样做? –

+0

我只是不想一次又一次地在所有的控制器中编写UIAlertAction代码。 –

+0

只是我想单身函数为整个应用程序创建UIAlertAction –

是的,你可以做到这一点。在您的实用工具类/共享类创建以下方法(无论你希望它是一类方法或实例方法将取决于你):

+(UIAlertAction *) createAlertActionWithSelector:(SEL) selector andTitle:(NSString *) title andAlertActionStyle:(UIAlertActionStyle) style andCallBackTarget:(id) target{ 
    UIAlertAction *action; 

    action = [UIAlertAction actionWithTitle:title style:style handler:^(UIAlertAction * action) { 
     [target performSelector:selector]; 

    }]; 
    return action; 
} 

例如,如果你想创建一个标题的AlertAction “OK”,嵌入法“okButtonTapped”和UIAlertActionStyleDefault代码,你会这样称呼它:

UIAlertAction * okAction = [UtilityClass createAlertActionWithSelector:@selector(okButtonTapped) 
                    andTitle:@"OK" 
                  andAlertActionStyle:UIAlertActionStyleDefault 
                 andCallBackTarget:self]; 

这里CallbackTarget是什么类,你是从,所以我们这里路过self调用共享方法。 处理程序中执行的方法必须存在于callBackTargetClass中。

现在把它添加到您的UIAlertController像:

[alertController addAction:okAction]; 

只要确保创建要在处理程序块运行和方法选择传递给你的alertAction创方法的代码的方法。而已。

免责声明:它的工作原理,但它目前呈现出一个警告,因为选择是进行选择未知的选择可能会导致泄漏。看到这个answer那个警告

+0

感谢您的答案,它的工作,但问题是我想减少代码,但与此方法的语句数量是相同的。 –

+0

所以你可以建议我遵循这个单例方法,因为我在创建UIAlertAction的行数中的代码不会减少。 –

+0

@SumitDhariwal等什么?你应该把它放在一个实用程序/单例类中,并根据你的场景调用这个方法。 – NSNoob