[英]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.