dismissViewControllerAnimated 在块中无法工作

12

在显示UIAlertController后,我尝试关闭一个UIViewController

这是我的代码:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title 
                                                                         message:msg
                                                                  preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Accept" 
                                                   style:UIAlertActionStyleDefault 
                                                 handler:^(UIAlertAction *action)
             {
                 [self dismissViewControllerAnimated:YES completion:nil];
             }];

[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:^{}];

然而,self从未被解雇。 有人知道如何解决吗?

更新

如果我将[self dismissViewControllerAnimated:YES completion:nil];设置在块之外,它就有效了。

4个回答

13

只需使用[super.navigationController popViewControllerAnimated:YES];


1
是的...那就是我4个月前写的 :D - Daniel

8

如果有人遇到同样的问题,我是通过推送 UIViewController 的方式实现的,而不是使用 presentViewController:animated:completion:。这就是为什么应该使用[self.navigationController popViewControllerAnimated:YES];

奇怪的是,[self dismissViewControllerAnimated:YES completion:nil]; 在块外部起作用,在块内部则不起作用,我无法解释这个问题...


5

[self dismissViewControllerAnimated:YES completion:nil]会关闭当前正在显示的视图控制器(即“self”)所显示的任何视图控制器。你需要做的是在“self”的呈现视图控制器上运行相同的方法。例如:

[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

但是self(当前的UIViewController)是我想要关闭的视图。我尝试添加.parentViewController,但没有任何区别。 - Daniel
没错,你想要解除 "self"。"self.presentingViewController" 可能会做到这一点。更新答案。 - dwlz
在调试器中,“self.presentingViewController”和“self.parentViewController”都是空的吗? - dwlz
不,self.parentViewController 的类型是 XXXRootNavigationController - Daniel
self.presentingViewController 怎么样? - dwlz
self.presentingViewController 是空的。 - Daniel

2

您是否检查了块被调用的线程?如果不是线程1,则无法正确关闭视图,因为UI操作只能在线程1上执行。尝试创建一个用于关闭的方法,然后在主线程上调用它:

    ...handler {
     [self performSelectorOnMainThread:@selector(dismissModalView) withObject:nil waitUntilDone:NO];
}];

-(void)dismissModalView {
     [self dismissViewControllerAnimated:YES completion:nil];
}

是的,我尝试过了,但它没有起作用。顺便说一下,最短的选择器是performSelectorOnMainThread:withObject:waitUntilDone: - Daniel

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