Sean Dong
Sean Dong

Reputation: 615

iOS - update UILabel text periodically with our user interaction

I have some labels on my UI which show something like "2s ago", "1h ago"... Now I want to update them periodically without user interaction. How could I achieve that?

Upvotes: 0

Views: 379

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

Use NSTimer. When the screen opens and you display the label, decide when you want it updated next. Say, you just updated the labels saying "2s ago", and the next thing that you want your users to see is "1m ago". You schedule a timer task to fire in 58 seconds, and provide a callback selector that updates the label, and schedules the next firing of the timer.

Since you are likely to update using irregular intervals (60 seconds for the first hour, then 60 minutes for the next 23 hours; one day after that) you should set your timer up without repeating.

Do not forget to cancel the timer when the view disappears.

Upvotes: 2

Ken Kuan
Ken Kuan

Reputation: 798

With NSTimer

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel: userInfo:nil repeats:YES];

And update your label in updateLabel:

Upvotes: 0

Related Questions