2015-04-01 79 views
2

我正在Xamarin的iOS应用程序中工作。定时器在iOS中显示秒,分钟和小时Xamarin

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接口一样,我们必须在iOS中使用它来保持它运行?

+0

的迟到了这个问题。以下两个答案都提供了我所需要的。所以我给他们每一个upvote。 – durbnpoisn 2016-07-03 11:25:30

回答

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(); 
} 
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); 
    } 
} 
相关问题