Cant redraw UILabel after updating text

2019-07-06 23:21发布

问题:

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 ();
}

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.

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

回答1:

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 ();
   });
}