如何通过按钮和外部轻击来正确解雇UIAlertController?

时间:2016-10-19 10:12:28

标签: ios objective-c uialertcontroller

我很清楚存在类似的问题,但我认为我未能找到解决此问题的正确方法。

如果您只是看下面的代码,您可能会说它没有任何问题。但

如果我要在UIViewController上显示一个UIAlertController,它是通过以下代码从storyboard中调用的,使用alert控制器的按钮会先取消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];
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

  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];
}