Search code examples
iosiphoneuicollectionviewuiactivityindicatorview

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!


Solution

  • I think this might have something to do with threading (eg. the UI on main thread not being ready to animate the indicator). You could try something like the following:

    [activityIndicator performSelector:@selector(startAnimating:) withObject:nil afterDelay:1];

    This is just a possible suggestion though, you should try different variations and check which one forces the animation onto the main thread correctly and in a timely matter. Another variation:

    dispatch_async(dispatch_get_main_queue(), ^{
        [activityIndicator startAnimating];
    });