1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import SwiftUI
struct ProfileLinksLayout: Layout {
private let spacing: CGFloat = 8
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let result = arrange(subviews: subviews, width: proposal.width)
return result.size
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let result = arrange(subviews: subviews, width: bounds.width)
for (index, item) in result.items.enumerated() {
subviews[index].place(
at: CGPoint(x: bounds.minX + item.origin.x, y: bounds.minY + item.origin.y),
anchor: .topLeading,
proposal: ProposedViewSize(item.size)
)
}
}
private func arrange(subviews: Subviews, width: CGFloat?) -> (
size: CGSize, items: [(origin: CGPoint, size: CGSize)]
) {
let proposedWidth = width.flatMap { $0.isFinite ? max(0, $0) : nil }
let availableWidth = proposedWidth ?? .greatestFiniteMagnitude
var items: [(origin: CGPoint, size: CGSize)] = []
var horizontalOffset: CGFloat = 0
var verticalOffset: CGFloat = 0
var rowHeight: CGFloat = 0
var usedWidth: CGFloat = 0
for subview in subviews {
let size = subview.sizeThatFits(ProposedViewSize(width: proposedWidth, height: nil))
if horizontalOffset > 0 && horizontalOffset + size.width > availableWidth {
horizontalOffset = 0
verticalOffset += rowHeight + spacing
rowHeight = 0
}
items.append((CGPoint(x: horizontalOffset, y: verticalOffset), size))
usedWidth = max(usedWidth, horizontalOffset + size.width)
rowHeight = max(rowHeight, size.height)
horizontalOffset += size.width + spacing
}
return (CGSize(width: proposedWidth ?? usedWidth, height: verticalOffset + rowHeight), items)
}
}