This is Question Video

我使用SDWebImage遇到有关imageView的问题。
我更改用户的图像并已经获得新用户的图像URL,但是当我按下此ViewController时,它将首先显示旧图像并更改为新图像。
我怎么了
谢谢。

var avatar:String = "" // previous VC data pass to here

var photoImageView:UIImageView = { () -> UIImageView in
    let ui = GeneratorImageView()
    ui.backgroundColor = UIColor.clear
    ui.layer.masksToBounds = true
    ui.contentMode = .scaleAspectFill
    return ui
}()

override func viewDidLoad() {
    super.viewDidLoad()

    iconImageFromUrl(imageView: iconImageView, url: avatar, isResize: false)
}


func iconImageFromUrl(imageView:UIImageView, url:String,isResize:Bool) {

imageView.setShowActivityIndicator(true)
imageView.setIndicatorStyle(.gray)

imageView.sd_setImage(with: URL(string:url), placeholderImage: nil, options: .lowPriority, progress: nil
    , completed: { (image, error, cacheType, url) in

        guard image != nil else{
            imageView.image = resizeImage(image: #imageLiteral(resourceName: "defaultIcon"), newWidth: 50)
            return
        }

        DispatchQueue.global().async {
            let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch

            if data != nil
            {
                if let image = UIImage(data: data!)
                {
                    DispatchQueue.main.async {

                        if isResize == true{
                            imageView.image = resizeImage(image: image, newWidth: 250)
                        }else{
                            imageView.image = image
                        }
                    }
                }
            }
        }
})
}

最佳答案

sd_setImage方法写在UIImageView类别中。下载图像后,它会自行将图像设置在UIImageview上,并且在完成操作中,闭包也将返回已下载/缓存的UIImage

您不需要从imageUrl创建数据并再次设置它。如果要调整图像大小,可以在返回的图像上进行调整。

另外,您无需检查图像nil即可设置默认图像,只需将调整大小后的默认图像作为占位符图像传递即可

imageView.sd_setImage(with: URL(string:url), placeholderImage: resizeImage(image: #imageLiteral(resourceName: "defaultIcon"), newWidth: 50), options: .lowPriority, progress: nil
, completed: { (image, error, cacheType, url) in
    guard image != nil else {
        return
    }

    if isResize {
          imageView.image = resizeImage(image: image, newWidth: 250)
    } })

关于ios - 快速使用SdWebImage和Image Change,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45025544/

10-13 03:51