我想在倒数计时器(此处设置为 10 秒)达到 0 秒时切换到新的 View Controller 。它使用下面的线程逻辑来做到这一点。标签通常显示倒计时“10、9、8、7”,但由于我使用了 ViewDidAppear,它没有显示。最后它会闪烁 0 秒,并且将发生 segue。我需要倒计时来显示整个时间,但无法弄清楚它是如何以及为什么消失的
使用系统计时器; 使用 System.Threading;
... 私有(private) System.Timers.Timer mytimer; 私有(private) int countSeconds;
...
public override void ViewDidLoad()
{
base.ViewDidLoad();
mytimer = new System.Timers.Timer();
//Trigger event every second
mytimer.Interval = 1000; //1000 = 1 second
mytimer.Elapsed += OnTimedEvent;
countSeconds = 10; // 300 seconds
mytimer.Enabled = true;
mytimer.Start();
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
countSeconds--;
int seconds = countSeconds % 60;
int minutes = countSeconds / 60;
string DHCountdownTime = (countSeconds / 60).ToString() + ":" + (countSeconds % 60).ToString("00"); //to give leading 0. so 9 seconds isnt :9 but :09
InvokeOnMainThread(() =>
{
lblTimer.Text = DHCountdownTime;
});
if (countSeconds == 0)
{
mytimer.Stop();
}
}
...
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
Thread.Sleep(countSeconds * 1000);
PerformSegue("DHSegue", this);
...
最佳答案
您的 Thread.Sleep
正在阻塞 UI 线程:
Thread.Sleep(countSeconds * 1000);
使用任务(或另一个线程)以允许 UI 线程继续处理消息:
await Task.Delay(countSeconds * 1000);
关于c# - ViewDidAppear 导致我的标签消失(Xamarin.ios,C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52171276/