仅当图像无法加载SDWebImage时才设置占位符图像

Ank*_*pta 5 ios sdwebimage swift

我想显示imageview的背景颜色,直到下载正在进行,如果下载失败或图像不可用,那么我想显示占位符图像.我怎样才能实现这一目标?

主要目的是稍后在加载期间不设置图像.

谢谢

Als*_*ler 5

来自SDWebImage 文档:

使用块

使用块,您可以收到有关图像下载进度以及图像检索成功与否的通知:

// Here we use the new provided sd_setImageWithURL: method to load the web image
Run Code Online (Sandbox Code Playgroud)

对于Swift:

cell.imageView.sd_setImageWithURL(url, placeholderImage:nil, completed: { (image, error, cacheType, url) -> Void in
            if (error) {
                // set the placeholder image here

            } else {
                // success ... use the image
            }
        })
Run Code Online (Sandbox Code Playgroud)

对于Objective-C

    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:nil
                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                    if (error) {
                                      self.imageView.image = [UIImage imageNamed:@"placeHolderImage"];
                                    }
                                 }];
Run Code Online (Sandbox Code Playgroud)

  • 谢谢我也是自己做的.干得好.如果你喜欢我的问题并发现它也适合投票. (2认同)

Ank*_*pta 5

Swift 3解决方案:

cell.imageView?.sd_setImage(with: url) { (image, error, cache, urls) in
            if (error != nil) {
                cell.imageView.image = UIImage(named: "ico_placeholder")
            } else {
                cell.imageView.image = image
            }
}
Run Code Online (Sandbox Code Playgroud)

目标C的解决方案:

[cell.imageView sd_setImageWithURL:url
                  placeholderImage:nil
                         completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                if (error) {
                                  self.imageView.image = [UIImage imageNamed:@"ico_placeholder"];
                                } else {
                                  self.imageView.image = image;
                                }
}];
Run Code Online (Sandbox Code Playgroud)

希望你们觉得这有用。