UIAlertAction完成块未被调用 - iOS

14

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

一切都很好,除了一个问题,完成块由于某种原因没有被调用。

这是我的代码:

// 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,那么它就会运行...为什么?感谢您的时间,丹。
2个回答

44

不要尝试关闭警告控制器,因为在调用警告动作处理程序时,它将自动关闭。

将“取消”操作更改为:

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

1
为什么要点踩?如果回答有问题,至少解释一下问题所在。 - rmaddy
3
我不知道谁把你的回答投了反对票,但我会给它点赞并标记为解决了我的问题,非常感谢。想想看,我也不知道为什么认为我需要告诉它关闭警告控制器。 - Supertecnoboff
因为它帮助了我,而且我以前也曾经被莫名其妙地点踩过,所以我点赞了。SO 应该要求在点踩时必须给出理由。 - Alyoshak

3
“取消”操作不应像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 被关闭。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接