我正在尝试创建一个计时器,它每次更新标签,这是我到目前为止所拥有的:
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
,但我无法更新或重绘 View 。
更新 timerLabel.text
后如何才能重绘 View ?
最佳答案
标签未更新,因为 System.Timers.Timer 在单独的线程上调用处理程序。您不能在主线程以外的线程中更改 ui 元素。
附上要在主线程上执行的处理程序代码:
private void TimerOnTick (object obj, EventArgs ea)
{
this.InvokeOnMainThread(delegate {
timerLabel.Text = DateTime.Now.ToString ();
timerLabel.SetNeedsDisplay ();
});
}
关于iphone - 更新文本后无法重绘 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6000741/