【问题标题】:If <UIAlertViewDelegate> is deprecated, how can I make my Alert button to do an action?如果 <UIAlertViewDelegate> 已弃用,我怎样才能让我的警报按钮执行操作?
【发布时间】:2016-09-18 16:07:09
【问题描述】:

我们曾经在ViewController.h 中使用UIAlertViewDelegate 来制作我们的自定义警报按钮来执行操作,例如在警报窗口中按下再次播放按钮会使游戏重新启动。

我们如何使用UIAlertControllerUIAlertView 的替换类)来做到这一点?

我阅读了 Apple 提供的以下文档,但没有看到提到的委托方法。这是否意味着我们不再这样做了?

https://developer.apple.com/reference/uikit/uialertcontroller

【问题讨论】:

标签: ios objective-c delegates uialertcontroller


【解决方案1】:
  • 先添加UIAlertController

  • 然后添加UIAlertAction

  • 然后将 action 添加到您的 alert controller

如下所示。

UIAlertController *myalert = [UIAlertController alertControllerWithTitle:@"your title" message:@"your messate" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *myaction = [UIAlertAction actionWithTitle:@"you title" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //your action here
    }];


    [myalert addAction:myaction];
    [self presentViewController:myalert animated:YES completion:nil];

【讨论】:

  • "//your action here" 部分对我来说特别重要。谢谢!
【解决方案2】:

正如您所发现的,UIAlertView 已被弃用(从 iOS 8 开始),UIAlertViewDelegate 也是如此。

您应该改用UIAlertControllerUIAlertController 使用不同的方法来处理用户对按钮的点击。在 UIAlertController 中,您将 UIAlertAction 对象添加到警报控制器。

UIAlertAction 采用一段代码,当用户触发该操作时会调用该代码块。您无需在协议中设置侦听消息的委托,而是将处理程序块(闭包)传递给您设置的每个按钮操作。这是解决同一问题的不同方法。

@AnuradhS 提供了显示热设置的示例代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2011-04-23
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多