Countdown refresh button
I have implemented a refresh button of style UIBarSystemItem which will be disabled for 10s whenever it is pressed.
I want to further improve it by showing the time left before it is enabled. What is the quickest way to do it?
Many thanks in advance.
Called whenever the button is pressed.
-(void)refreshButton {
[self performSelector:@selector(enableRefreshButton) withObject:nil afterDelay:10];
self.navigationItem.rightBarButtonItem.enabled = NO;
}
-(void)enableRefreshButton {
self.navigationItem.rightBarButtonItem.enabled = YES;
}
EDIT: The refresh button is of style UIBARSystemItemRefresh.
I am currently doing this as the answer suggests I use NSTimer. The button does get enabled and disable accordingly but the text doesn't change.
@inteface ... {
int count;
}
-(void)viewDidLoad{
UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonPressed)];
self.navigationItem.rightBarButtonItem = refresh;
}
-(void)refreshButtonPressed {
//do something here...
count = 10;
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimeLeft) userInfo:nil repeats:YES];
}
-(void)updateTimeLeft{
count --;
NSLog(@"%i", count);
self.navigationItem.rightBarButtonItem.title = [NSString stringWithFormat:@"%i", count];
self.navigationItem.rightBarButtonItem.enabled = NO;
if (count == 0) {
self.navigati开发者_JS百科onItem.rightBarButtonItem.enabled = YES;
[self.myTimer invalidate];
}
}
Can I use the title
property with UIBarButtonSystemItem?
For this you need to implement NSTimer
declare int
variable count
in .h file. and initialize it with count==10
in viewDidLoad/viewWillAppear
as your code goes.
call this method in performSelector
- (void)updateCount:(NSTimer *)aTimer {
count--;
self.navigationItem.rightBarButtonItem.enabled = YES;
self.navigationItem.rightBarButtonItem.title = [NSString stringWithFormat:@"%d",count];
NSLog(@"%i", count);
if (count == 0) {
self.navigationItem.rightBarButtonItem.enabled = NO;
self.navigationItem.rightBarButtonItem.title = [NSString stringWithFormat:@"YOUR BAR BUTTON NAME"];
[timer invalidate];
timer = nil;
}
}
EDIT
I think this link would definitely solved problem. This is almost same as you were asking. Please go through the link. http://www.richardhyland.com/diary/2008/12/21/some-cool-tips-and-tricks-for-the-iphone-sdk/
You could use this method
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
精彩评论