Reputation: 39
Hi i want use progress bar in my iPhone app based on time like if one person start journey starts at 10:00 Am and finished at 11:00 Am then for every 5 minutes i will update the progress comparing with current time, how is it possible
Upvotes: 0
Views: 4524
Reputation: 6065
iVars:
NSDate *_startDate = ....
NSDate *_finishDate = ....
UIProgressBarView *_progressBar = ....
triggerMethod:
- (void)start
{
[self updateProgressBar];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:updateInterval
target:self
selector:@selector(updateProgressBar)
userInfo:nil
repeats:YES];
}
update progressbarview
- (void)updateProgressBar
{
NSTimeInterval diff = [_finishDate timeintervalSince:_startDate];
NSTimeInterval pastTime = [_finishDate timeIntervallSinceNow];
[_progressBar setProgress:pastTime/diff animated:YES];
}
Do not forget to invalidate timer when it is finished and in dealloc method.
If you save your finish and start date somewhere else in your code. Then you can recreate the view with same state even it is deallocated. It means the user do not need have open that view 1 hour. eg. he/she close and open after 30 min.
Upvotes: 0
Reputation: 130222
You could use a simple NSTimer
to achieve this:
In viewDidLoad
of course, these variables will need to be declared in your header file.
UIProgressView *myProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
float someFloat = 0;
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(methodToUpdateProgress) userInfo:nil repeats:YES];
Then this will update the progress view (assuming min/max value is 0-100)
- (void)methodToUpdateProgress
{
if(someFloat == 100){
[myTimer invalidate];
}else{
someFloat = someFloat + 12;
[myProgressView setProgress:someFloat animated:YES];
}
}
Additionally, if the time at which this is called is actually a concern this example should help you a lot. Quoted From: How do I use NSTimer?
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: 1
target: self
selector:@selector(onTick:)
userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
NOTE: This is a pretty rough example, but it should get the point across. Hope this helps!
Upvotes: 2