更新文本后无法重绘UILabel [英] Cant redraw UILabel after updating text

查看:57
本文介绍了更新文本后无法重绘UILabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个计时器,该计时器每隔一个滴答声都会更新标签,这是我到目前为止所拥有的:

I'm trying to create a timer which updates a label every tick, This is what I have so far:

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 ,但无法获取更新或重绘的视图.

But this doesn't update the label. In debug I can see that timerLabel.Text is being set, but I cant get the view to update or redraw.

更新 timerLabel.text 后,如何重新绘制视图?

How can I get my view to redraw after I update my timerLabel.text?

推荐答案

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

The label is not being updated because System.Timers.Timer invokes the handler on a separate thread. You cannot change ui elements in a thread other than the main.

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

Enclose your handler code to be executed on the main thread:

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

这篇关于更新文本后无法重绘UILabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆