c# - ViewDidAppear 导致我的标签消失(Xamarin.ios,C#)

标签 c# ios xamarin xamarin.ios xamarin-studio

我想在倒数计时器(此处设置为 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/

相关文章:

c# - LINQ Any - 总是返回 false

c# - 搭建 MYSQL 数据库时出现错误 : The method or operation is not implemented.

iphone 5 Default-568h@2x.png 图像在模拟器上有效,但在实际设备上无效

ios - 我可以将用户名附加到Hockey App的崩溃报告中吗?

c# - 使用 C# 在 Windows 8 上获取当前线程 ID

c# - 我应该如何将我的商业模式与我的观点联系起来?

objective-c - XCode 4,签名无效 (-19011)

ios - 从 iOS 应用程序中删除应用程序内购买选项

c# - 将 azure 存储客户端库与 xamarin 结合使用

android - Xamarin.Android EditText 事件未在设备上触发