ios - 如何使用 SDWebImage - Swift 在 imageURL 为空时设置默认图像

标签 ios swift sdwebimage

我在 cellForRowAt 函数中有以下代码:

    let url = URL(string: myurl!)
   cell.empPhoto.image? = (cell.empPhoto.image?.circle)!
   cell.empPhoto.image? = (cell.empPhoto.image?.rounded)!

    cell.empPhoto.sd_setImage(with: url)

我正在使用 SDWebImage 中的 sd_setImage 从 url 下载图像并缓存它,但有时 url 找不到或内容为空,那么如何为单元格提供默认图像,如果url 是空的,我应该在使用 sd_setImage 之前检查 url 的内容还是我可以从同一个库中完成它?

我想要的是这样的:

     if url.hasImage {
       cell.empPhoto.sd_setImage(with: url)
     }
      else{ // use default image
        cell.empPhoto.image=UIImage(named: "contact")
     }

最佳答案

您可以使用此版本的sd_setImage 方法:

cell.empPhoto.sd_setImageWithURL(url, placeholderImage:UIImage(imageNamed:"placeholder.png"))
如果 url 不包含有效图像,

placeholderImage 将是默认图像。

附加说明:您可能需要查看 Kingfisher , 它的 build 灵感来自 SDWebImage ,但它是使用 Swift 构建的吗?

关于ios - 如何使用 SDWebImage - Swift 在 imageURL 为空时设置默认图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39879088/

相关文章:

uiimageview - SDWebImage和设置自定义HTTP header ?

IOS以编程方式设置文本字段的宽度

ios - 防止 iPhone 应用程序用户登录到多个设备

Swift:实例变量优先于类构造函数?

ios - 在静态上下文中引用 'self'

ios - 根据使用 SDWebImage 下载的图像高度更改 imageView 高度约束后 TableView 单元格未调整大小(AUTOLAYOUT)

iphone - 推送或本地通知提醒用户在已保存数据和远程数据之间进行更改

android - 打开特定应用的权限设置 flutter ?

ios - MBProgressHUD 导致 iOS 应用程序崩溃(Swift 2.0)

ios - 在 Collection View 中不失真地显示图像的正确方法是什么