Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIActivityIndicatorView not spinning in UICollectionViewCell

I have a custom cell that is loaded at the bottom of my collection view. Its only job is to display an activity indicator view - which happens while the app is making a new work call.

So I added it to the cell like so:

BBLoaderCell *loaderCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LoaderCell" forIndexPath:indexPath];


UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityIndicator.hidesWhenStopped = YES;
activityIndicator.hidden = NO;
activityIndicator.center = loaderCell.imageView.center;
activityIndicator.tag = 10;

[loaderCell.imageView addSubview:activityIndicator];

    [activityIndicator startAnimating];
    return loaderCell;

This shows an activity indicator in the last cell of my view - however it does not spin. Any ideas?

Solution Found

As per comments - it was a threading issue. I also took the suggestion to move the code to the custom nib file for the cell.

here is the refactored code:

BBLoaderCell *loaderCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LoaderCell" forIndexPath:indexPath];
    loaderCell.backgroundColor = [UIColor clearColor];

     if (self.loadingMore == NO){
        dispatch_async(dispatch_get_main_queue(), ^{
            activityIndicator.hidden = YES;
            [loaderCell.spinner stopAnimating];
        });
    }
     else if (self.loadingMore == YES){
    dispatch_async(dispatch_get_main_queue(), ^{
        activityIndicator.hidden = NO;
        [loaderCell.spinner startAnimating];
    });
    }

    return loaderCell;

This is working as I need it to.

Thanks guys!

like image 230
Robert J. Clegg Avatar asked Mar 18 '14 08:03

Robert J. Clegg


1 Answers

You most likely call reloadData more than once in a very short time. Maybe already in the next frame. The activity indicator hides when stops by default. This is what happens:

  1. At first reloadData it shows the spinner
  2. A second reloadData reloads also the cell and the spinner hides itself
  3. Now the spinner is hidden
  4. You scroll around but the cell get's reused. The spinner is still hidden

You can set activityIndicator.hidesWhenStopped = false. The spinner should now be always visible. But it's not spinning.

Adding this will resume the spinning.

override func prepareForReuse() {
   activityIndicator.startAnimating()
}

Another issue might be the color. Maybe the spinner has the same color as the background. Try to set the color of the spinner like this:

activityIndicator.color = .red

You can check if the spinner is there by using the "Debug View Hierarchy" Button Debug View Hierarchie

It will show you the wireframe of the current visible screen Wireframe

like image 169
zeiteisen Avatar answered Sep 29 '22 11:09

zeiteisen