Search code examples
xamarin.iosuialertviewxamarin-studio

Yes/No Confirmation UIAlertView


I usually use the following code for a confirmation alert

int buttonClicked = -1;
UIAlertView alert = new UIAlertView(title, message, null, NSBundle.MainBundle.LocalizedString ("Cancel", "Cancel"),
                                    NSBundle.MainBundle.LocalizedString ("OK", "OK"));
alert.Show ();
alert.Clicked += (sender, buttonArgs) =>  { buttonClicked = buttonArgs.ButtonIndex; };

// Wait for a button press.
while (buttonClicked == -1)
{
    NSRunLoop.Current.RunUntil(NSDate.FromTimeIntervalSinceNow (0.5));
}

if (buttonClicked == 1)
{
    return true;
}
else
{
    return false;
}

This doesn't appear to be working in iOS7. The loop just continues to run and the Clicked event never seems to get fired. Does anyone have a working example of how to do a confirmation alert?


Solution

  • Alex Corrado wrote this beautiful sample that you can use with await:

    // Displays a UIAlertView and returns the index of the button pressed.
    public static Task<int> ShowAlert (string title, string message, params string [] buttons)
    {
        var tcs = new TaskCompletionSource<int> ();
        var alert = new UIAlertView {
            Title = title,
            Message = message
        };
        foreach (var button in buttons)
            alert.AddButton (button);
        alert.Clicked += (s, e) => tcs.TrySetResult (e.ButtonIndex);
        alert.Show ();
        return tcs.Task;
    }
    

    Then you do instead:

    int button = await ShowAlert ("Foo", "Bar", "Ok", "Cancel", "Maybe");