2016-10-19 2 views
0

Я хорошо знаю, что подобные вопросы существуют, но я думаю, что не смог найти правильное решение этой проблемы.Как правильно убрать UIAlertController как с помощью кнопки, так и нажимать на нее?

Если вы могли бы просто взглянуть на код ниже, вы можете сказать, что в этом нет ничего плохого. BUT,

Если я собираюсь отобразить UIAlertController на UIViewController, который вызывается из раскадровки по следующему коду, с помощью кнопки контроллера предупреждения отклоняет первый 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]; 
} 

Как я могу это исправить?

+0

UIAlertController * контроллер объявляет globlly, а затем выполнить операцию –

+0

ваш код является правильным. вам не нужно объявлять контроллер UIAlertController * глобально. в вашем коде есть и другие проблемы. –

+0

@balkaransingh, я прошу отличаться. Я только что открыл еще один проект в xcode и снова проверил его. Результат такой же –

ответ

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

я боюсь, ничего не изменилось –

+0

я просто делаю это одной демонстрацией и в этом демо полностью работает. с какой проблемой вы сталкиваетесь –

+0

Представьте, что у вас есть приложение, которое отображает различные названия автомобилей на TableVC и спецификации каждого автомобиля в деталяхVC. И вы вызвали detailVC, как первый код, который я обсуждал. --- Теперь в деталяхVC есть кнопка, отображающая UIAlertController. С этим кодом, если я прикасаюсь за пределы UIAlertController, это нормально, но если я увожу его, нажав кнопку, входящую в систему alertcontroller, он закрывает как контрольный, так и текущий viewcontroller. Поэтому я перешел обратно в tableVC –

Смежные вопросы