Kurztipp - Reload-Button mit Countdown (iOS)

From macwrench
Jump to navigation Jump to search

Mit dem foldenden Codebeispiel für iOS wird ein Reload Button (UIBarButtonItem) erstellt, das sich bei Benutzung in einen Countdown verwandelt und währenddessen blockiert ist:

- (void)viewDidLoad {
	
	/* ... */
	
	[super viewDidLoad];
	
	/* ... */
	
	self.reloadItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadAction:)];
	self.navigationItem.leftBarButtonItem = self.reloadItem;
	
	/* ... */
	
}

- (IBAction)reloadAction:(id)sender {
	
	/* ... */
	
	// display countdown  and re-enable button after a few seconds:
	NSInteger timeToEnable = 10; // seconds
	self.reloadItem = [[UIBarButtonItem alloc] initWithTitle:[NSString stringWithFormat:@"%d",(int)timeToEnable] style:UIBarButtonItemStylePlain target:self action:@selector(reloadAction:)];
	[self.navigationItem setLeftBarButtonItem:self.reloadItem animated:YES];
	self.reloadItem.enabled = NO;
	__block void (^runCountdownBlock)(int) = ^(int i) {
		self.reloadItem.title = [NSString stringWithFormat:@"%d", i];
		if(i>0) {
			dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC);
			dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
				runCountdownBlock(i-1);
			});
		} else {
			self.reloadItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadAction:)];
			self.navigationItem.leftBarButtonItem = self.reloadItem;
			self.reloadItem.enabled = YES;
			runCountdownBlock = nil; // Breaking retain cycle
		}
	};
	runCountdownBlock(10);
	
	/* ... */
	
}