Last active
March 28, 2022 15:25
-
-
Save isaac-weisberg/61bd148b8d11c9ee09513ea031690416 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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