iOS SDWebImage fade in new image

后端 未结 8 1355
北海茫月
北海茫月 2021-01-31 06:36

I\'ve been using SDWebImage on my iPhone app to handle all of the image loading. I am using a placeholder image, and I want to crossfade or fade in the new image once it loads.

相关标签:
8条回答
  • 2021-01-31 07:07

    Here is the code which help me out and working great.

    photoImageView.sd_imageTransition = .fade
    photoImageView.sd_setImage(with: URL(string: imageUrl), completed: nil)
    
    0 讨论(0)
  • 2021-01-31 07:10

    This is Swift 4 version of @Zoltan Varadi answer:

    extension UIImageView {
        public func sd_setImageWithURLWithFade(url: URL!, placeholderImage placeholder: UIImage!) {
            self.sd_setImage(with: url, placeholderImage: placeholder) { (image, error, cacheType, url) -> Void in
                if let downLoadedImage = image {
                    if cacheType == .none {
                        self.alpha = 0
                        UIView.transition(with: self, duration: 0.3, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { () -> Void in
                            self.image = downLoadedImage
                            self.alpha = 1
                        }, completion: nil)   
                    }
                } else {
                    self.image = placeholder
                }
            }
        }
    }
    

    I changed the duration to 0.3

    You can add this function to the extension in order you need the completionHandler block:

    public func sd_setImageWithURLWithFade(url: URL!, placeholderImage placeholder: UIImage!, comple: @escaping (Bool)->()) {
        self.sd_setImage(with: url, placeholderImage: placeholder, options: .allowInvalidSSLCertificates) { (image, error, cacheType, url) in
            if let downLoadedImage = image {
                if cacheType == .none {
                    self.alpha = 0
                    UIView.transition(with: self, duration: 0.3, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { () -> Void in
                        self.image = downLoadedImage
                        self.alpha = 1
                    }, completion: { _ in
                        comple(true)
                    })
                }
            } else {
                self.image = placeholder
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题