[英]Modal UIAlertController in non async method with return type
我目前有一种必须实现的方法,需要确切的签名。 我不能添加async
,因为它返回bool
并且我不能使返回类型Task<bool>
。 该方法显示模式UIAlertController并等待结果。 一旦UIAlertController被关闭,它需要返回结果。 目前,该方法不起作用,因为PresentViewController
是一个阻止调用。 因此,UIAlertController永远不会显示,因此应用程序卡在了那里。
方法如下:
public static bool ShowYesNoMessage(string title, string message)
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
UIAlertController alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
alertController.AddAction(UIAlertAction.Create("Yes", UIAlertActionStyle.Default, (action) => tcs.TrySetResult(true)));
alertController.AddAction(UIAlertAction.Create("No", UIAlertActionStyle.Default, (action) => tcs.TrySetResult(false)));
//Gets the currently visible view controller and present from this one
UIHelper.CurrentViewController.PresentViewController(alertController, true, null);
tcs.Task.Wait();
return tcs.Task.Result;
}
在诸如“ ShowYesNoMessage”之类的阻塞调用中等待方法的结果时,有没有办法保持UI更新? 也许是一种与iOS相关的方法,可以防止UI冻结模式UIAlertController? 也许是呈现模态视图的另一种方法?
您可以使用WaitHandle
等待用户响应。 可能不是最好的解决方法,但应该可以。
public static bool ShowYesNoMessage(string title, string message)
{
var resetEvent = new AutoResetEvent(false);
var result = false;
// Run in another thread so it doesn't block
Task.Run(action: () =>
{
var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
alertController.AddAction(
UIAlertAction.Create(
"Yes",
UIAlertActionStyle.Default,
(action) =>
{
result = true;
resetEvent.Set();
}));
alertController.AddAction(
UIAlertAction.Create(
"No",
UIAlertActionStyle.Default,
(action) =>
{
result = false;
resetEvent.Set();
}));
InvokeOnMainThread(() => UIHelper.CurrentViewController.PresentViewController(alertController, true, null));
});
resetEvent.WaitOne();
return result;
}
注意 :代码未经测试
编辑:该代码可能仍将阻止,但请告诉我它如何进行。 我不在Mac电脑旁,因此无法对其进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.