Skip to content

Instantly share code, notes, and snippets.

@starsite
Last active June 7, 2019 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starsite/454f4cd9ecf52e8fff6926691153850e to your computer and use it in GitHub Desktop.
Save starsite/454f4cd9ecf52e8fff6926691153850e to your computer and use it in GitHub Desktop.
import UIKit
import Kingfisher
class EventTableViewCell: UITableViewCell {
@IBOutlet weak var eventPhoto: UIImageView!
@IBOutlet weak var eventDescription: UITextView!
// constraint
var aspectConstraint: NSLayoutConstraint? {
didSet {
if oldValue != nil {
eventPhoto.removeConstraint(oldValue!)
}
if aspectConstraint != nil {
eventPhoto.addConstraint(aspectConstraint!)
}
}
}
// clear
override func prepareForReuse() {
super.prepareForReuse()
aspectConstraint = nil
}
// set image, called in cellForRow
func setCustomImage(url: URL, width: CGFloat, height: CGFloat) {
let aspect = width / height
let constraint = NSLayoutConstraint(
item: eventPhoto,
attribute: .width,
relatedBy: .equal,
toItem: eventPhoto,
attribute: .height,
multiplier: aspect,
constant: 0.0
)
constraint.priority = UILayoutPriority(999)
aspectConstraint = constraint
// kf
OperationQueue.main.addOperation {
self.eventPhoto.kf.setImage(
with: url,
placeholder: nil,
options: [.transition(.fade(0.3))],
progressBlock: nil,
completionHandler: { _ in
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment