【问题标题】:ViewDidAppear is causing my label to dissapear (Xamarin.ios, C#)ViewDidAppear 导致我的标签消失(Xamarin.ios,C#)
【发布时间】:2019-02-09 18:45:15
【问题描述】:

当倒数计时器(此处设置为 10 秒)达到 0 秒时,我想继续使用新的视图控制器。它使用下面的线程逻辑来做到这一点。标签通常显示倒计时“10、9、8、7”,但由于我使用了 ViewDidAppear,所以它没有显示。最后它会闪烁 0 秒,然后会发生转场。我需要倒计时来显示整个时间,并且无法弄清楚它消失的方式和原因

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

... 私有 System.Timers.Timer mytimer; 私有 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】:

    您的Thread.Sleep 阻塞了 UI 线程:

    Thread.Sleep(countSeconds * 1000);             
    

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

    await Task.Delay(countSeconds * 1000);
    

    【讨论】:

    • 是的,使用任务和异步确实是要走的路。谢谢!
    • @AndrewBolaji 没问题,尽可能接受答案,快乐编码
    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多