dismissViewControllerAnimated does not work within a block

家住魔仙堡 提交于 2019-11-30 14:56:54

问题


I try to close a UIViewController after an UIAlertController has been shown.

This is my code:

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:^{}];

However, self never gets dismissed. Anyone knows how to solve this?

UPDATE

if I set [self dismissViewControllerAnimated:YES completion:nil]; outside of the block, it works.


回答1:


Just use [super.navigationController popViewControllerAnimated:YES];




回答2:


In case someone is having the same issue. I pushed the UIViewController, I didn't present it with presentViewController:animated:completion:. That's why [self.navigationController popViewControllerAnimated:YES]; should be used instead.

The strange thing is that [self dismissViewControllerAnimated:YES completion:nil]; worked outside of the block and didn't inside, I have no explanation for this...




回答3:


[self dismissViewControllerAnimated:YES completion:nil] will close any view controllers that the currently displaying view (i.e., "self") is displaying. What you want to do is run this same method on the presenting view controller for "self". I.e.

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



回答4:


Have you checked on which thread the block is being called on? If it's not thread 1, then it won't dismiss your view properly, as UI manipulation can only be done on thread one. Try creating a method for dismissing and then calling it on the main thread:

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

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


来源:https://stackoverflow.com/questions/28070015/dismissviewcontrolleranimated-does-not-work-within-a-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!