Skip to content

Instantly share code, notes, and snippets.

@pilot34
Last active May 23, 2020 22:32
Show Gist options
  • Save pilot34/f8531206314f5f60d742ee726f493cd8 to your computer and use it in GitHub Desktop.
Save pilot34/f8531206314f5f60d742ee726f493cd8 to your computer and use it in GitHub Desktop.
class MyView: UIView {
private var preferredMaxLayoutWidth: CGFloat? {
didSet {
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
override var intrinsicContentSize: CGSize {
return performLayout(changeFrames: false, width: preferredMaxLayoutWidth)
}
override func layoutSubviews() {
let width = bounds.size.width
if width == UIView.layoutFittingExpandedSize.width {
preferredMaxLayoutWidth = performLayout(changeFrames: false, width: nil).width
} else if preferredMaxLayoutWidth != bounds.size.width {
preferredMaxLayoutWidth = bounds.size.width
} else {
_ = performLayout(changeFrames: true, width: preferredMaxLayoutWidth)
super.layoutSubviews()
}
}
private func performLayout(changeFrames: Bool, width: CGFloat?) -> CGSize {
// calculate new size here depends on width
// change subviews frames if changeFrames == true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment