web-dev-qa-db-fra.com

Comment rejeter UIAlertController lorsque vous appuyez sur en dehors de UIAlertController?

Comment rejeter UIAlertController lorsque vous tapez en dehors de UIAlertController?

Je peux ajouter un UIAlertAction de style UIAlertActionStyleCancel pour ignorer le UIAlertController.

Mais je veux ajouter la fonction qui, lorsque l'utilisateur appuie sur en dehors de UIAlertController, le UIAlertController sera rejeté. Comment faire ça? Merci.

40
leizh00701

Ajoutez une action d'annulation distincte avec le style UIAlertActionStyleCancel. Ainsi, lorsque l'utilisateur appuie sur l'extérieur, vous obtenez le rappel.

Obj-c

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"A Message" preferredStyle:UIAlertControllerStyleActionSheet];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
 // Called when user taps outside
}]];

Swift 5.

let alertController = UIAlertController(title: "Alert Title", message: "A Message", preferredStyle: .actionSheet)             
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { 
    action in
         // Called when user taps outside
}))
37
Vivek Yadav

Si vous ciblez des appareils ayant iOS> 9.3 et utilisant Swift et preferredStyle est Alert, vous pouvez utiliser un extrait de code comme ci-dessous:

func showAlertBtnClicked(sender: UIButton) {
    let alert = UIAlertController(title: "This is title", message: "This is message", preferredStyle: .Alert)
    self.presentViewController(alert, animated: true, completion:{
        alert.view.superview?.userInteractionEnabled = true
        alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped)))
    })
}

func alertControllerBackgroundTapped()
{
    self.dismissViewControllerAnimated(true, completion: nil)
}

Avec Swift 3:

func showAlertBtnClicked(sender: UIButton) {
    let alert = UIAlertController(title: "This is title", message: "This is message", preferredStyle: .alert)
    self.present(alert, animated: true) {
        alert.view.superview?.isUserInteractionEnabled = true
        alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped)))
    }
}

func alertControllerBackgroundTapped()
{
    self.dismiss(animated: true, completion: nil)
}
38
chancyWu

Swift, Xcode 9

Ignorer AlertController avec le bouton Annuler

fournit une action à votre alertController où le style de UIAlertAction est .cancel

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)

À l'aide de cette méthode, alertController sera ignoré lorsque l'utilisateur appuiera sur le bouton pour annuler le bouton d'action, ainsi qu'en dehors de alertController.

si vous ne souhaitez pas que l'utilisateur quitte alertController après une retouche en dehors de alertController, désactivez l'interaction utilisateur des premières sous-vues de alertController à la clôture de la méthode actuelle.

self.present(alertController, animated: true) {
     alertController.view.superview?.subviews[0].isUserInteractionEnabled = false
    }

Ignorer AlertController lors des retouches en dehors de la vue Contrôleur

Si vous ne souhaitez pas annuler le bouton dans la vue de votre contrôleur et que vous souhaitez exclure le contrôleur lorsque l'utilisateur doit effectuer des retouches en dehors de la vue du contrôleur, faites-le.

self.present(alertController, animated: true) {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissAlertController))
        alertController.view.superview?.subviews[0].addGestureRecognizer(tapGesture)
}

@objc func dismissAlertController(){
    self.dismiss(animated: true, completion: nil)
}
16

Si vous utilisez Swift:

Ajouter une action avec addAction(_:) et style:UIAlertActionStyle.Cancel.

Le gestionnaire `sera appelé lorsque vous appuierez sur le bouton ou en dehors du cadre.

var alertVC = UIAlertController(...) // initialize your Alert View Controller

        alertVC.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
            (alertAction: UIAlertAction!) in
            alertVC.dismissViewControllerAnimated(true, completion: nil)
        }))

Objective-C:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:...];


[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
   [alertVC dismissViewControllerAnimated:YES completion:nil];
}]];
7
Kevin Machado

Swift 4:

Ignorer la feuille d'action lorsque l'utilisateur tape en dehors de la feuille d'action créée à l'aide de UIAlertController

Extrait de code:

// Declare Action Sheet reference
var actionSheet: UIAlertController!

// Init and Show Action Sheet
func showActionSheetClicked(sender: UIButton) {

    // Init Action Sheet
    actionSheet = UIAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet)

    self.present(actionSheet, animated: true) {
        // Enabling Interaction for Transperent Full Screen Overlay
        self.actionSheet.view.superview?.subviews.first?.isUserInteractionEnabled = true

        // Adding Tap Gesture to Overlay
        self.actionSheet.view.superview?.subviews.first?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.actionSheetBackgroundTapped)))
    }
}

// To dismiss Action Sheet on Tap
@objc func actionSheetBackgroundTapped() {
    self.actionSheet.dismiss(animated: true, completion: nil)
}
2
Muthukumar Chinnu
- (void)addBackgroundDismissTapForAlert:(UIAlertController *)alert {
    if (!alert.view.superview) {
        return;
    }
    alert.view.superview.userInteractionEnabled = YES;
    [alert.view.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(alertControllerBackgroundTapped)]];
    for (UIView *subV in alert.view.superview.subviews) {
        if (subV.width && subV.height) {
            subV.userInteractionEnabled = YES;
            [subV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(alertControllerBackgroundTapped)]];
        }
    }
}
- (void)alertControllerBackgroundTapped {

    [self dismissViewControllerAnimated: YES
                         completion: nil];
}
1
songxing10000

Le moyen le plus simple dans Obj-C:

UIAlertController *alert = [UIAlertController alertControllerWithTitle: ...
[self presentViewController:alert animated:YES completion:^{
                                       [alert.view.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alertControllerBackgroundTapped)]];
                                   }];

et alors:

- (void)alertControllerBackgroundTapped
{
    [self dismissViewControllerAnimated: YES
                             completion: nil];
}
1
oskarko

Le moyen le plus simple:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self button];

}

- (void) button {
    UIButton * AlertButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [AlertButton setTitle:@"Button" forState:UIControlStateNormal];
    AlertButton.frame = CGRectMake((self.view.frame.size.width/2) - 50 , (self.view.frame.size.height/2) - 25, 100, 50);
    [AlertButton addTarget:self action:@selector(Alert) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:AlertButton];
}

- (void)Alert {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController: alert animated: YES completion:^{ alert.view.superview.userInteractionEnabled = YES; [alert.view.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(DismissAlertByTab)]]; }];
}

- (void)DismissAlertByTab
{
    [self dismissViewControllerAnimated: YES completion: nil];
}
0
Ibrahim

Si vous affichez le débogage de la vue d'ensemble de l'alerte, vous verrez que ce n'est pas aussi simple que d'ajouter un outil de reconnaissance des gestes tactiles à la vue UITransitionView de _UIAlertControllerView.Vous pouvez le faire à la place.

[presenter presentViewController:alertController animated:YES completion:^{
    NSArray <UIView *>* superviewSubviews = alertController.view.superview.subviews;
    for (UIView *subview in superviewSubviews) {
        if (CGRectEqualToRect(subview.bounds, weakSelf.view.bounds)) {
            [subview addSingleTapGestureWithTarget:weakSelf action:@selector(dismissModalTestViewController)];
        }
    }
}];
0
Michael Lorenzo
    UIView *alertView = self.alertController.view;
UIView *superPuperView = self.alertController.view.superview;
CGPoint tapCoord = [tap locationInView:superPuperView];
if (!CGRectContainsPoint(alertView.frame, tapCoord)) {
    //dismiss alert view
}
0
Slashik