Skip to content

Instantly share code, notes, and snippets.

@isaac-weisberg
Last active March 28, 2022 15:25
Show Gist options
  • Save isaac-weisberg/61bd148b8d11c9ee09513ea031690416 to your computer and use it in GitHub Desktop.
Save isaac-weisberg/61bd148b8d11c9ee09513ea031690416 to your computer and use it in GitHub Desktop.
import UIKit
class AutoscaleImageView: UIImageView {
var aspectRatioConstraint: NSLayoutConstraint?
override init(image: UIImage?) {
super.init(image: image)
recalculateAspectRatioConstraint()
}
override init(image: UIImage?, highlightedImage: UIImage?) {
super.init(image: image, highlightedImage: highlightedImage)
recalculateAspectRatioConstraint()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
recalculateAspectRatioConstraint()
}
override var image: UIImage? {
didSet {
recalculateAspectRatioConstraint()
}
}
func recalculateAspectRatioConstraint() {
if let image = image {
let size = image.size
let ratio = size.width / size.height
if ratio != aspectRatioConstraint?.multiplier {
aspectRatioConstraint?.isActive = false
let aspectRatioConstraint = widthAnchor.constraint(equalTo: heightAnchor, multiplier: ratio)
self.aspectRatioConstraint = aspectRatioConstraint
aspectRatioConstraint.isActive = true
}
} else {
aspectRatioConstraint?.isActive = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment