如何通过按钮和点击外部来正确地解散UIAlertController



我很清楚类似的问题存在,但我认为我没有看到一个合适的解决方案。

如果你能看看下面的代码,你可能会说它没有什么问题。但是,

如果我要在一个UIViewController上显示一个UIAlertController,这个UIViewController是通过下面的代码从storyboard调用的,使用button of alert controller首先解散UIAlertController然后解散我的UIViewController。所以我导航回我的初始视图控制器

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
[vc setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentViewController:vc animated:NO completion:NULL];

这是UIAlertController的代码:

- (IBAction)myAlertAction:(id)sender {
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"Title"
                                                                        message:@"Lorem ipsum dolor sit amet"
                                                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [controller addAction:alertAction];
    [self presentViewController:controller animated:YES completion:^{
        controller.view.superview.userInteractionEnabled = YES;
        [controller.view.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(alertControllerBackgroundTapped)]];
    }];
}
- (void)alertControllerBackgroundTapped
{
    [self dismissViewControllerAnimated: YES
                             completion: nil];
}

我怎么能解决这个问题?

  UIAlertController *controller;

- (IBAction)Btn_alert:(id)sender {
    controller = [UIAlertController alertControllerWithTitle:@"Title"
                                                     message:@"Lorem ipsum dolor sit amet"
                                              preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                              {
                                  //Do some thing here
                                  [controller dismissViewControllerAnimated:YES completion:nil];
                                   [self.presentedViewController presentingViewController];
                              }];
    [controller addAction:alertAction];
    [self presentViewController:controller animated:YES completion:^{
        controller.view.superview.userInteractionEnabled = YES;
        [controller.view.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(alertControllerBackgroundTapped)]];
    }];
}
- (void)alertControllerBackgroundTapped
{
       [controller dismissViewControllerAnimated:YES completion:nil];
}

最新更新