Show activity indicator in SDWebImage

前端 未结 18 1392
独厮守ぢ
独厮守ぢ 2021-01-30 09:20

I\'m using SDWebView image and i want to show an Activity Indicator as placeholder, while fetching the image from remote.

I tried Malek\'s answer here How to show an act

18条回答
  •  余生分开走
    2021-01-30 09:36

    With updated library (Resolved Crash on iOS 8), we have below method -

    - (void)sd_setImageWithURL:(NSURL *)url 
    {
        [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
    }
    

    As we can see the option to add progress block and completed block, we can simply add Activity indicator in progress block and remove in completion block.

    Customized method to add Activity Indicator here -

    - (void)sd_setImageWithURL:(NSURL *)url {
    
        [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            UIActivityIndicatorView *activity = nil;
            activity = (UIActivityIndicatorView *)[self viewWithTag:100000];
            if (!activity) {
                activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                [activity setTag:100000];
                [activity setHidesWhenStopped:YES];
                [activity setCenter:CGPointMake(self.frame.size.width/2.0f,self.frame.size.height/2.0f)];
                [self addSubview:activity];
            }
            else {
                [activity setCenter:CGPointMake(self.frame.size.width/2.0f,self.frame.size.height/2.0f)];
            }
            [activity startAnimating];
    
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[self viewWithTag:100000];
            if ([activity isKindOfClass:[UIActivityIndicatorView class]]) {
                [activity stopAnimating];
            }
        }];
    }
    

    This will add UIActivityIndicatorView to the center of UIImageView when image downloading in progress and remove on completion.

提交回复
热议问题