Skip to content

Instantly share code, notes, and snippets.

@damirstuhec
Created November 22, 2022 10:47
Show Gist options
  • Save damirstuhec/d2fc7e3617b06aa39c254c653ad8a4a6 to your computer and use it in GitHub Desktop.
Save damirstuhec/d2fc7e3617b06aa39c254c653ad8a4a6 to your computer and use it in GitHub Desktop.
Correction to Majid's sizeThatFits implementation in https://swiftwithmajid.com/2022/11/16/building-custom-layout-in-swiftui-basics
struct FlowLayout: Layout {
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
var totalHeight: CGFloat = 0
var totalWidth: CGFloat = 0
var lineWidth: CGFloat = 0
var lineHeight: CGFloat = 0
for size in sizes {
if lineWidth + size.width > proposedSize.width {
totalHeight += lineHeight
lineWidth = size.width
lineHeight = size.height
} else {
lineWidth += size.width
lineHeight = max(lineHeight, size.height)
}
totalWidth = max(totalWidth, lineWidth)
}
totalHeight += lineHeight
return .init(width: totalWidth, height: totalHeight)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment