是/否确认UIAlertView

Jon*_*013 5 uialertview xamarin.ios xamarin-studio

我通常使用以下代码来确认警报

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;
}
Run Code Online (Sandbox Code Playgroud)

这似乎不适用于iOS7.循环只是继续运行,Clicked事件似乎永远不会被触发.有没有人有一个如何做确认警报的工作示例?

mig*_*aza 34

Alex Corrado写了这个漂亮的样本,你可以等待:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

然后你改为:

int button = await ShowAlert ("Foo", "Bar", "Ok", "Cancel", "Maybe");
Run Code Online (Sandbox Code Playgroud)

  • 只是注意到这一点,e.ButtonIndex将无法在我的机器上编译,因为TrySetResult正在寻找一个nint.您需要将其强制转换为nint或将Task更改为Task <nint> (3认同)