【问题标题】:UIAlertAction completion block not called - iOS未调用 UIAlertAction 完成块 - iOS
【发布时间】:2015-06-15 19:24:32
【问题描述】:

我有一个带有 UIAlertController 的 iOS 应用程序,当用户点击按钮时,我的应用程序中会以操作表的形式呈现。

这一切都很好,除了一件事,完成块由于某种原因没有被调用。

这是我的代码:

// Setup the alert information/type.
UIAlertController *action_view = [UIAlertController alertControllerWithTitle:@"Test title" message:@"test message" preferredStyle:UIAlertControllerStyleActionSheet];

// Create and add the cancel button.
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {

    [action_view dismissViewControllerAnimated:YES completion:^{
        NSLog(@"asdhfgjk");
    }];
}];

// Add the action button to the alert.
[action_view addAction:cancel];

// Present the alert to the user.
[self presentViewController:action_view animated:YES completion:nil];

如果您运行该代码,您将看到关闭控制器的行不会运行,其中的 NSLog 语句也不会运行。但是,如果您删除 NSLog 并将完成块设置为 nil,那么它确实会运行....为什么???

感谢您的宝贵时间,丹。

【问题讨论】:

    标签: ios objective-c cocoa-touch uiactionsheet uialertcontroller


    【解决方案1】:

    不要试图关闭警报控制器。在调用警报操作的处理程序时,它将为您解除。

    将“取消”操作更改为:

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        NSLog(@"asdhfgjk");
    }];
    

    【讨论】:

    • 为什么投反对票?如果答案有问题,至少说明问题所在。
    • 我不知道谁投了你的票,但我投票赞成你的答案并勾选它,因为它完美地解决了我的问题,谢谢。想一想,我不知道为什么我的印象是无论如何我都需要告诉它关闭警报控制器。
    • 投了赞成票,因为它对我有帮助,而且我之前也被投了反对票,但没有给出任何理由。 SO 应该要求在否决时给出一个理由。
    【解决方案2】:

    “取消”操作不应该像 rmaddy 提到的那样关闭视图控制器。但是,即使“取消”操作设置为:

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
    NSLog(@"asdhfgjk");}];
    

    您可能会看到未调用完成块的相同问题。例如,实现这个(有点做作的)方法:

    - (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion {
       [[self presentedViewController] dismissViewControllerAnimated:flag completion:nil];
    }
    

    也可能有这种效果,因为 UIAlertController 在调用完成块之前被解除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多