Dimitar
Dimitar

Reputation: 2402

Cant redraw UILabel after updating text

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?

Upvotes: 3

Views: 4361

Answers (1)

Dimitris Tavlikos
Dimitris Tavlikos

Reputation: 8170

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

Upvotes: 6

Related Questions