Last active
April 5, 2023 09:22
-
-
Save marcc-orange/e309d86275e301466d1eecc8e400ad00 to your computer and use it in GitHub Desktop.
An image view that can computes its intrinsic height from its width while preserving aspect ratio
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 | |
/// An image view that computes its intrinsic height from its width while preserving aspect ratio | |
/// Source: https://stackoverflow.com/a/48476446 | |
class ScaledHeightImageView: UIImageView { | |
// Track the width that the intrinsic size was computed for, | |
// to invalidate the intrinsic size when needed | |
private var layoutedWidth: CGFloat = 0 | |
override var intrinsicContentSize: CGSize { | |
layoutedWidth = bounds.width | |
if let image = self.image { | |
let viewWidth = bounds.width | |
let ratio = viewWidth / image.size.width | |
return CGSize(width: viewWidth, height: image.size.height * ratio) | |
} | |
return super.intrinsicContentSize | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
if layoutedWidth != bounds.width { | |
invalidateIntrinsicContentSize() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks so much!
Here's a slightly refactored version: