import SwiftUI /// Lays its subviews out in a row, starting a new row where the next one doesn't fit. A subview /// wider than the whole width gets the whole width. public struct FlowLayout: Layout { public var spacing: CGFloat public var lineSpacing: CGFloat public init(spacing: CGFloat = 5, lineSpacing: CGFloat = 3) { self.spacing = spacing self.lineSpacing = lineSpacing } public func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { let frames = place(subviews, width: proposal.width ?? .infinity) let width = frames.map(\.maxX).max() ?? 0 return CGSize(width: proposal.width.map { min($0, width) } ?? width, height: frames.map(\.maxY).max() ?? 0) } public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { for (subview, frame) in zip(subviews, place(subviews, width: bounds.width)) { subview.place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY), proposal: ProposedViewSize(frame.size)) } } /// Each subview's frame, in rows from the top left. private func place(_ subviews: Subviews, width: CGFloat) -> [CGRect] { var frames: [CGRect] = [] var x: CGFloat = 0 var y: CGFloat = 0 var rowHeight: CGFloat = 0 for subview in subviews { var size = subview.sizeThatFits(.unspecified) if size.width > width { size = subview.sizeThatFits(ProposedViewSize(width: width, height: nil)) } if x > 0, x + size.width > width { x = 0 y += rowHeight + lineSpacing rowHeight = 0 } frames.append(CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: min(size.width, width), height: size.height))) x += size.width + spacing rowHeight = max(rowHeight, size.height) } return frames } }