Xamarin iOS:实现从UIAlertView对话框返回值的方法

时间:2017-10-23 07:35:58

标签: c# methods xamarin.ios uialertview

我需要实现一个返回从UIAlertView接收的用户输入的方法。

这是我到目前为止所做的:

无论用户输入文本是什么,它都会返回字符串的初始值。有什么想法吗?

    private string GetUserInput()
    {
        string userInput = string.Empty;

        UIAlertView alert = new UIAlertView();
        alert.Title = "What is your favourite movie?";
        alert.AddButton("OK");
        alert.AddButton("Cancel");
        alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
        alert.Clicked += (object s, UIButtonEventArgs ev) =>
        {
            if (ev.ButtonIndex != 0) return;

            userInput = alert.GetTextField(0).Text;

        };

        alert.Show();

        return userInput;
    }

解决方案:

我找到了解决方案。如果有人需要,我把它放在下面。

string userInput = await Methods.ShowAlert("What is your favourite movie?", "", "OK", "Cancel");

ShowAlert方法:

public static Task<string> ShowAlert(string title, string message,params string[] buttons)
{
    var tcs = new TaskCompletionSource<string>();
    var alert = new UIAlertView
    {
        Title = title,
        Message = message,
        AlertViewStyle = UIAlertViewStyle.PlainTextInput

    };

    foreach (var button in buttons)
        alert.AddButton(button);

    alert.Clicked += (s, e) =>
    {
        if (e.ButtonIndex != 0) return;
        tcs.TrySetResult(alert.GetTextField(0).Text);
    };
    alert.Show();

    return tcs.Task;
}

1 个答案:

答案 0 :(得分:-1)

var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(configurationTextField)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel))
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
    println("User click Ok button")
    println(self.textField.text)
}))
self.presentViewController(alert, animated: true, completion: {
    println("completion block")
})

<!-- end snippet -->