Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Created April 26, 2020 23:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayesh15111988/7ecf94709f3540f2ff68a2d4ab4f5c98 to your computer and use it in GitHub Desktop.
Save jayesh15111988/7ecf94709f3540f2ff68a2d4ab4f5c98 to your computer and use it in GitHub Desktop.
//
// MovieCell.swift
//
import UIKit
final class MovieCell: UITableViewCell {
let posterImageView = UIImageView(frame: .zero)
// A previous URL temporarily stored to keep track of previous URL vs. current URL since cells are being reused
var previousUrlString: String?
// MARK: initializer
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
layoutViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
posterImageView.contentMode = .scaleAspectFill
posterImageView.clipsToBounds = true
}
private func layoutViews() {
posterImageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(posterImageView)
// Constraints for posterImageView
NSLayoutConstraint.activate([
posterImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
posterImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
posterImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
posterImageView.widthAnchor.constraint(equalToConstant: Constants.imageWidth)
])
}
func apply(with urlString: String) {
posterImageView.image = UIImage(named: Constants.placeholderImageName)
ImageDownloader.shared.downloadImage(with: urlString, completionHandler: { (image, cached) in
// We will use two conditions here. Their description is as follows,
// Either image is cached, in which case it is returned synchronously. If image is not cached, it will be returned asynchronously, in which case we want to store the previous image URL and compare it against the most recent value represented by fullImageUrlString property associated with Movie object. If they do not match, do not apply the image since it now belongs to previous cell which has since been reused.
if cached || (urlString == self.previousUrlString) {
self.posterImageView.image = image
}
}, placeholderImage: UIImage(named: Constants.placeholderImageName))
previousUrlString = urlString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment