0

I am trying to attach a UITapGestureRecognizer to the View of a UIAlertController but the recognize event is never firing.

I am coding this in Xamarin, but I feel like the issue applies to native code as well.

InvokeOnMainThread(() =>

    var alert = new UIAlertController();
    alert.Title = "My Title";
    alert.Message = "My Message";

    UITapGestureRecognizer tapGestureRecognizer = new 
        UITapGestureRecognizer((gesture) =>
        {
            //I never get here
        });

    alert.View.AddGestureRecognizer(tapGestureRecognizer);
    alert.View.UserInteractionEnabled = true;

    this.PresentViewController(alert, true, null);
});

Ideally, I would like to dismiss the alert when a user touches the popup, but I can't seem to detect the gesture.

I've tried adding the recognizer both, before, and after the alert is presented.

Dave
  • 3,676
  • 4
  • 28
  • 39

1 Answers1

0

Solution:

To dismiss the UIAlertController by clicking the background View, you can add the tapGestureRecognizer to the last view in the screen when UIAlertController is popping up, check the code below:

public partial class ViewController : UIViewController
{
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        // Perform any additional setup after loading the view, typically from a nib.

        var alert = new UIAlertController();
        alert.Title = "My Title";
        alert.Message = "My Message";

        UIAlertAction ac1 = UIAlertAction.Create("123",UIAlertActionStyle.Cancel,null);

        alert.AddAction(ac1);

        this.PresentViewController(alert, true, addGesOnBackGround);
    }

    public void addGesOnBackGround() {

        UIView backView = new UIView();

        Array arrayViews = UIApplication.SharedApplication.KeyWindow.Subviews;

        if (arrayViews.Length >0)
        {
            backView = arrayViews.GetValue(arrayViews.Length-1) as UIView;               
        }

        UITapGestureRecognizer tapGestureRecognizer = new
         UITapGestureRecognizer((gesture) =>
         {
             //I never get here
             this.DismissViewControllerAsync(true);

         });

        backView.AddGestureRecognizer(tapGestureRecognizer);
        backView.UserInteractionEnabled = true;
    }

}
nevermore
  • 15,432
  • 1
  • 12
  • 30
  • This solution did not work for me. The gesture recognizer action is still not called. – Dave Jun 26 '19 at 11:34
  • @Dave I use the code and it works on my side. I upload a [sample here](https://github.com/XfHua/UIAlertViewController-xamarin.ios) and you can check it. Are you missing something? – nevermore Jun 27 '19 at 01:48