Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// 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
You can’t perform that action at this time.