objective-ciphoneuibarbuttonitemuiactivityindicatorviewrightbarbuttonitem

Replace UIBarButtonItem with UIActivityIndicatorView not working


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.