Replace UIBarButtonItem with UIActivityIndicatorView not working
-
28-09-2019 - |
Question
I want to replace refresh button with activity indicator when the user press the refresh button and after the tableview is refreshed, i want to change it back to refresh button. But when I press the refresh button, it didn't change to activity indicator but the refresh button is highlighted until the data reloading is finished.
the code is as below. Did I miss something?
-(void) reloadNewsStarted{
UIActivityIndicatorView *activityIndicatorRightBarItem = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[activityIndicatorRightBarItem startAnimating];
UIBarButtonItem *activityItem = [[UIBarButtonItem alloc] initWithCustomView:activityIndicatorRightBarItem];
[activityIndicatorRightBarItem release];
self.navigationItem.rightBarButtonItem = activityItem;
[activityItem release];
[self reloadNewsEnded];
}
-(void) reloadNewsEnded {
//reload data process
UIBarButtonItem *reloadNewsBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadNewsStarted)];
reloadNewsBtn.style = UIBarButtonItemStyleBordered;
self.navigationItem.rightBarButtonItem = reloadNewsBtn;
[reloadNewsBtn release]; }
Solution
Instead of writing
[self reloadNewsEnded];
Please write
[NSThread detachNewThreadSelector:@selector(reloadNewsEnded) toTarget:self withObject:nil];
this line start new thread in background so the activity indicator & the data reload will be done simultaneously in two thread.
OTHER TIPS
why is this line at the end of the reloadNewStarted
method
[self reloadNewsEnded];
it appears to just undo the changes to the button? You should be waiting until the action is complete before calling it
Changing the button isn't going to take effect until the run loop regains control from your code. It sounds like your reload operation is synchronous and blocks the event queue, which won't allow that to happen. If your processing takes a noticeable amount of time, you need to use either a background thread or asynchronous handling on the main run loop (for example, by using NSURLConnection to manage a network task and callbacks) so you don't block.