计时器显示iOS Xamarin中的秒,分钟和小时

ayu*_*nia 2 c# timer xamarin.ios ios xamarin

我正在开发Xamarin的iOS应用程序.

timer1 = new System.Timers.Timer();
timer1.Interval = 1000;

//Play.TouchUpInside += (sender,e)=>
//{
       timer1.Enabled = true;
       Console.WriteLine("timer started");
       timer1.Elapsed += new ElapsedEventHandler(OnTimeEvent);
//}
Run Code Online (Sandbox Code Playgroud)

这是我在viewdidload()中写的;

public void OnTimeEvent(object source, ElapsedEventArgs e)
{
    count++;
    Console.WriteLine("timer tick");
    if (count == 30)
    {
        timer1.Enabled = false;
        Console.WriteLine("timer finished");

        new System.Threading.Thread(new System.Threading.ThreadStart(() =>
        {
            InvokeOnMainThread(() =>
            {
                StartTimer.Text = Convert.ToString(e.SignalTime.TimeOfDay); // this works!
            });
        })).Start();
    }

    else
    {
        //adjust the UI
        new System.Threading.Thread(new System.Threading.ThreadStart(() =>
        {
            InvokeOnMainThread(() =>
            {
                StartTimer.Text = Convert.ToString(e.SignalTime.TimeOfDay); // this works!
            });
        })).Start();

        timer1.Enabled = false;
        Console.WriteLine("timer stopped");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我点击按钮播放时调用的事件.我希望这个方法继续运行,以便starttimer.Text在UI中的label()上更新时间.就像我们在Android中使用的Runnable Interface一样,我们必须在iOS中使用什么来保持它的运行?

Mar*_*cel 7

使用异步 - 更干净(没有编组让你再次回到主线程!)

private int _duration = 0;

public async void StartTimer() {
    _duration = 0;

    // tick every second while game is in progress
    while (_GameInProgress) {
        await Task.Delay (1000);
        _duration++;

        string s = TimeSpan.FromSeconds(_duration).ToString(@"mm\:ss");
        btnTime.SetTitle (s, UIControlState.Normal);
    }
}
Run Code Online (Sandbox Code Playgroud)