Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
JonBull2013 Avatar asked Oct 01 '13 16:10

JonBull2013


3 Answers

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");
like image 139
miguel.de.icaza Avatar answered Jan 03 '23 14:01

miguel.de.icaza


Classic one! You're showing the alert view before adding the event handler.

Also, as a bonus, I'd recommend you to use the Async/Await features instead using buttonClicked. Take a look, it's awesome!

like image 45
kbtz Avatar answered Jan 03 '23 14:01

kbtz


Could try something like this hope it helps

var Confirm  = new UIAlertView("Confirmation", "Are you Sure ",null,"Cancel","Yes");
                Confirm.Show();
                Confirm.Clicked += (object senders, UIButtonEventArgs es) => 
                {
                    if (es.ButtonIndex == 0 ) {
                                           // do something if cancel
                    }else
                    {
                        // Do something if yes
                    }
                };
like image 21
pjapple15 Avatar answered Jan 03 '23 15:01

pjapple15