Skip to content

Instantly share code, notes, and snippets.

@BigZaphod
Created July 15, 2023 05:16
Show Gist options
  • Save BigZaphod/602407bce524c7a2bba7c79c53396d0d to your computer and use it in GitHub Desktop.
Save BigZaphod/602407bce524c7a2bba7c79c53396d0d to your computer and use it in GitHub Desktop.
struct TestLayout: Layout {
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
// Assuming this layout is in a fixed size container and isn't sizing itself based on the subviews.
return proposal.replacingUnspecifiedDimensions()
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let availableWidth = bounds.size.width
let offeredWidth = availableWidth / CGFloat(subviews.count)
let subviewProposal = ProposedViewSize(width: offeredWidth, height: bounds.size.height)
let subviewWidths = subviews.map { $0.sizeThatFits(subviewProposal).width }
let totalSubviewWidth = subviewWidths.reduce(0) { $0 + $1 }
let amountOfSpace = availableWidth - totalSubviewWidth
let gapSize = amountOfSpace / CGFloat(subviews.count + 1)
var pos = bounds.origin
for i in subviews.indices {
pos.x += gapSize
subviews[i].place(at: pos, proposal: subviewProposal)
pos.x += subviewWidths[i]
}
}
}
struct ContentView: View {
var body: some View {
TestLayout {
Color.red.frame(width: 20)
Color.green.frame(width: 50)
Color.blue.frame(width: 30)
}
.frame(width: 300, height: 30)
.border(.black)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment