I am trying to implement a simple quiz app on the iphone in the spirit of learning, part of this app is a timer.
I want my timer to count down from 10 to 0. I had a simple NSTimer that repeats and calls a method every second and in this method I update a label which displays the remaining time, which works nicely.
Now instead of displaying the timer using a label I wanted to use a graphical progress bar, so I created ten images, one full in length (representing 10), the next 9/10 of the size and so on, and in my repeating timer method instead of updating a label I update a UIImage with the appropriate image so over time the progress bar gets smaller and smaller.
My problem is that due to the way I have implemented the progress bar, it doesn't look very smooth when it updates every second. Is there another way I should approach developing this kind of functionality? I have heard that you could use a stretchable image to get a smoother effect but I couldn't see any good examples of that.
Any advice and code samples welcome, just trying to learn here.
After investigating a few options I have decided to use a UIProgressView (suggested by sudo in comments) coupled with a NSTimer which updates the progress ten times a second for ten seconds, I used this solution because:
Using the code below assume I have a UIProgressView variable named 'progressView', an NSTimer named 'timer' and a floating point variable named 'time', then:
Another way I investigated (after seeing Disco's comments) but decided against was to use animation. In this instance I created two png images, named 'redbar.png' and 'greenbar.png', the idea bring they would be placed over each other (the green bar being on top/in the foreground), and over the duration of the animation the green bar shrinks, revealing the red bar in the background.
An ideal solution would be to combine the UIProgressView and the UIAnimation block, but this is not currently an option (see this question animate a UIProgressView's change).
Hope this helps someone in the future.
EDIT::
It appears the ideal solution I mention above is now available in iOS5, taken from the apple reference site:
setProgress:animated: Adjusts the current progress shown by the receiver, optionally animating the change.
May not be what you're looking for but may help you. Why not have a
UIImageView
with your image at full size then apply someUIView
animations to it over a set duration? This way the shrinking will be smooth.This may be what you're looking for, I'm not sure. Just seems a bit easier than using ten different images.
I did by increasing the setting progress from (0.01 - 1.00) to (0.001 - 1.000) and decrease the time difference between setting progress values.
Here is my below code with three different speeds of animation.