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

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

当倒数计时器(此处设置为10秒)达到0秒时,我想要切换到新的视图控制器。它使用下面的线程逻辑来做到这一点。标签通常显示倒计时“10,9,8,7”,但由于我使用了ViewDidAppear,它没有显示。最后它将闪烁0秒,并且将发生segue。我需要倒计时来显示整个时间,并且无法弄清楚它是如何以及为什么会消失

使用System.Timers;使用System.Threading;

...私人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);

...

c# ios xamarin xamarin.ios xamarin-studio
1个回答
1
投票

你的Thread.Sleep阻止了UI线程:

Thread.Sleep(countSeconds * 1000);             

使用任务(或其他线程)以允许UI线程继续处理消息:

await Task.Delay(countSeconds * 1000);
© www.soinside.com 2019 - 2024. All rights reserved.