问题
Imagine I have a UIProgressView that is showing the progress of some task (in this case triggered by a timer at a set interval).
Under normal circumstances this works fine. It starts off at 0, so in my initial call to animate the progress view, everything works as expected.
However, when I need to reset the progress, things start breaking.
Imagine I have the following sequence of events:
- The user initiated a refresh, and so the progress view begins animating with a timer.
- After several seconds, the progress view has reached 70%.
- Before it can advance further, the user has initiated another refresh.
I would like the progress bar to be reset to 0 unanimated, and then fire off the first step of the animation immediately. When I try to do so, it is as though the first call (reset to 0) is completely ignored, and instead I get an animation from 70% to 10%. (I.e. the progress bar is moving backwards!)
I don't want the progress to ever move backwards during an animation.
Here is my code:
- (void)beginAnimation {
// omitted: clear the timer
[self.progressView setProgress:0 animated:NO];
[self.progressView setProgress:0.1 animated:YES];
// omitted: fire off a timer to trigger every few seconds and advance the progress
}
回答1:
Essentially, we want to schedule the animation on the next run loop.
In this case, I was able to do so by using dispatch_async():
- (void)beginAnimation {
// omitted: clear the timer
[self.progressView setProgress:0 animated:NO];
dispatch_async(dispatch_get_main_queue(), ^{
// Animate on the next run loop so the animation starts from 0.
[self.progressView setProgress:0.1 animated:YES];
});
// omitted: fire off a timer to trigger every few seconds and advance the progress
}
来源:https://stackoverflow.com/questions/24213703/reset-uiprogressview-and-begin-animating-immediately