更新文本后无法重绘UILabel

时间:2011-05-14 08:47:50

标签: iphone xamarin.ios

我正在尝试创建一个计时器,每个刻度都更新一个标签,这是我到目前为止所做的:

public override void ViewDidLoad ()
{
    timer = new Timer ();
    timer.Elapsed += new ElapsedEventHandler (TimerOnTick);
    timer.Interval = 1000;
    timer.Start ();
}

private void TimerOnTick (object obj, EventArgs ea)
{
   timerLabel.Text = DateTime.Now.ToString ();
   timerLabel.SetNeedsDisplay ();
}

但这不会更新标签。在调试中我可以看到timerLabel.Text正在设置,但我无法让视图更新或重绘。

在更新timerLabel.text后,如何让我的视图重绘?

1 个答案:

答案 0 :(得分:6)

标签未更新,因为System.Timers.Timer在单独的线程上调用处理程序。您不能在主要线程之外的线程中更改ui元素。

附上要在主线程上执行的处理程序代码:

private void TimerOnTick (object obj, EventArgs ea)
{
   this.InvokeOnMainThread(delegate {
       timerLabel.Text = DateTime.Now.ToString ();
       timerLabel.SetNeedsDisplay ();
   });
}