ViewDidAppear 导致我的标签消失(Xamarin.ios,C#)
ViewDidAppear is causing my label to dissapear (Xamarin.ios, C#)
我想在倒数计时器(此处设置为 10 秒)达到 0 秒时切换到新的视图控制器。它使用下面的线程逻辑来做到这一点。标签通常显示倒计时“10、9、8、7”,但由于我使用了 ViewDidAppear,它没有显示。最后它会闪烁 0 秒,并且将发生 segue。我需要倒计时来显示整个时间,但无法弄清楚它是如何以及为什么消失的
使用System.Timers;
使用 System.Threading;
...
私人 System.Timers. 计时器 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);
我想在倒数计时器(此处设置为 10 秒)达到 0 秒时切换到新的视图控制器。它使用下面的线程逻辑来做到这一点。标签通常显示倒计时“10、9、8、7”,但由于我使用了 ViewDidAppear,它没有显示。最后它会闪烁 0 秒,并且将发生 segue。我需要倒计时来显示整个时间,但无法弄清楚它是如何以及为什么消失的
使用System.Timers; 使用 System.Threading;
... 私人 System.Timers. 计时器 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);