消息未使用计时器在UIAlertController中更新

问题描述 投票:0回答:1

我正在尝试在UIAlertController中添加倒数计时器消息,计时器会正确触发,并在每次触发时登录控制台。但是alertController的消息不会更新。我尝试在计时器正常工作之外更新消息。不知道为什么它在计时器内不起作用。这是我的代码:

var ttimer = new System.Timers.Timer(1000);

alertController = UIAlertController.Create("title", "initial message", UIAlertControllerStyle.Alert);
using (var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (t) => { ttimer.Stop(); ttimer.Dispose(); }))
{
    alertController.AddAction(cancelAction);
}
PresentViewController(alertController, true, null);

var counter = 5; // 5 seconds count down timer, dismiss alert after 5 seconds

ttimer.Elapsed += (Object source, ElapsedEventArgs e) =>
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
        e.SignalTime); // This logs to the console fine
    if (counter > 0)
    {
        counter--;
        alertController.Message ="new message"; // This doesn't work
    }
    else
    {
        alertController.DismissViewController(false, null); // This doesn't work
        ttimer.Stop();
        ttimer.Dispose();
    }
};

ttimer.AutoReset = true;
ttimer.Enabled = true;

alertController.Message = "new message for testing"; // This works

我做错了什么?这是在Xamarin iOS / C#中。

c# timer xamarin.ios
1个回答
0
投票

Elapsed事件未在主线程上发生。您可以将UI更新强制为use the UI thread

InvokeOnMainThread ( () => {
  alertController.Message ="new message";
});
© www.soinside.com 2019 - 2024. All rights reserved.