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.
Here is the code which help me out and working great.
photoImageView.sd_imageTransition = .fade
photoImageView.sd_setImage(with: URL(string: imageUrl), completed: nil)
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
}
}
}