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

时间:2015-04-01 12:10:26

标签: c# ios timer xamarin.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);
//}

这是我在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");
    }
}

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

1 个答案:

答案 0 :(得分:4)

//before loading the view
public override void ViewWillAppear(bool animated)
{
    ...
    StartTimer();
}
// when view is loaded  
public override void ViewDidLoad()
{
    base.ViewDidLoad();
    ....
    UpdateDateTime();
}

private void UpdateDateTime()
{
    var dateTime = DateTime.Now;
    StartTimer.Text = dateTime.ToString("HH:mm:ss");
}

private void StartTimer()
{
    var timer = new Timer(1000);
    timer.Elapsed += (s, a) => InvokeOnMainThread(UpdateDateTime);
    timer.Start();
}