Search code examples
c#iphoneipadxamarin.ios

Messagebox.Show and DialogResult equivalent in MonoTouch


I have a Yes/No dialog from UIAlertView with two buttons. I would like in my method to implement the logic similar to this:

if(messagebox.Show() == DialogResult.OK)

The thing is if I call UIAlertView.Show() the process continues. But I need to wait for the result of user interaction and return true or false depanding on clicking the second button. Is this possible in MonoTouch?


Solution

  • To do this, what you can do is to run the mainloop manually. I have not managed to stop the mainloop directly, so I instead run the mainloop for 0.5 seconds and wait until the user responds.

    The following function shows how you could implement a modal query with the above approach:

    int WaitForClick ()
    {
        int clicked = -1;
        var x = new UIAlertView ("Title", "Message",  null, "Cancel", "OK", "Perhaps");
        x.Show ();
        bool done = false;
        x.Clicked += (sender, buttonArgs) => {
            Console.WriteLine ("User clicked on {0}", buttonArgs.ButtonIndex);
        clicked = buttonArgs.ButtonIndex;
        };    
        while (clicked == -1){
            NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5));
            Console.WriteLine ("Waiting for another 0.5 seconds");
        }
    
        Console.WriteLine ("The user clicked {0}", clicked);
        return clicked;
    }