Created
November 22, 2022 10:47
-
-
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
This file contains hidden or 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
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