Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Last active January 31, 2024 19:00
Show Gist options
  • Save chriseidhof/3c6ea3fb2102052d1898d8ea27fbee07 to your computer and use it in GitHub Desktop.
Save chriseidhof/3c6ea3fb2102052d1898d8ea27fbee07 to your computer and use it in GitHub Desktop.
SwiftUI Flow Layout
//
// ContentView.swift
// DeleteMe
//
// Created by Chris Eidhof on 02.02.21.
//
import SwiftUI
/*
To calculate a flow layout, we need the sizes of the collection's elements. The "easiest" way to do this seems to be using preference keys: these are values that a child view can set and that get propagated up in the view hierarchy.
A preference key consists of two parts: a type for the data (this needs to be equatable) and a type for the key itself.
*/
struct MyPreferenceKeyData: Equatable {
var size: CGSize
var id: AnyHashable
}
struct MyPreferenceKey: PreferenceKey {
typealias Value = [MyPreferenceKeyData]
static var defaultValue: [MyPreferenceKeyData] = []
static func reduce(value: inout [MyPreferenceKeyData], nextValue: () -> [MyPreferenceKeyData]) {
value.append(contentsOf: nextValue())
}
}
// Next up, we create a wrapper view which renders it's content view, but also propagates its size up the view hierarchy using the preference key.
struct PropagatesSize<ID: Hashable, V: View>: View {
var id: ID
var content: V
var body: some View {
content.fixedSize().background(GeometryReader { proxy in
Color.clear.preference(key: MyPreferenceKey.self, value: [MyPreferenceKeyData(size: proxy.size, id: AnyHashable(self.id))])
})
}
}
// This is a flow layout directly taken from the Swift Talk episode on flow layouts (even though it's written for UIKit, we can reuse it without modification).
struct FlowLayout {
let spacing: UIOffset
let containerSize: CGSize
init(containerSize: CGSize, spacing: UIOffset = UIOffset(horizontal: 10, vertical: 10)) {
self.spacing = spacing
self.containerSize = containerSize
self.width = containerSize.width
}
var currentX = 0 as CGFloat
var currentY = 0 as CGFloat
var lineHeight = 0 as CGFloat
var width: CGFloat
mutating func add(element size: CGSize) -> CGRect {
if currentX + size.width > containerSize.width {
currentX = 0
width = max(width, size.width)
currentY += lineHeight + spacing.vertical
lineHeight = 0
}
defer {
lineHeight = max(lineHeight, size.height)
currentX += size.width + spacing.horizontal
}
return CGRect(origin: CGPoint(x: currentX, y: currentY), size: size)
}
var size: CGSize {
return CGSize(width: width, height: currentY + lineHeight)
}
}
/*
Finally, here's the collection view. It works as following:
It contains a collection of `Data` and a way to construct `Content` from an element of `Data`.
For each value of `Data`, it wraps the element in a `PropagatesSize` container, and then collects all those sizes to construct the layout.
*/
struct OverallHeightPreference: PreferenceKey {
static var defaultValue: CGFloat = 10
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
struct CollectionView<Data, Content>: View where Data: RandomAccessCollection, Data.Element: Identifiable, Content: View {
var data: Data
@State private var sizes: [MyPreferenceKeyData] = []
var content: (Data.Element) -> Content
@State private var height: CGFloat = 10
func layout(size: CGSize) -> (items: [AnyHashable:CGSize], size: CGSize) {
var f = FlowLayout(containerSize: size)
var result: [AnyHashable:CGSize] = [:]
for s in sizes {
let rect = f.add(element: s.size)
result[s.id] = CGSize(width: rect.origin.x, height: rect.origin.y)
}
return (result, f.size)
}
func withLayout(_ laidout: (items: [AnyHashable:CGSize], size: CGSize)) -> some View {
return ZStack(alignment: .topLeading) {
ForEach(self.data) { el in
PropagatesSize(id: el.id, content: self.content(el))
.offset(laidout.items[AnyHashable(el.id)] ?? .zero)
}
.preference(key: OverallHeightPreference.self, value: laidout.size.height)
}
.onPreferenceChange(MyPreferenceKey.self, perform: {
self.sizes = $0
})
.onPreferenceChange(OverallHeightPreference.self, perform: { value in
self.height = value
})
}
var body: some View {
return GeometryReader { proxy in
self.withLayout(self.layout(size: proxy.size))
}.frame(height: height)
}
}
// Just a temporary hack to make things work
extension Int: Identifiable {
public var id: Int {
return self
}
}
struct ContentView: View {
let items: [String] = (1..<10).map { num in
"Element \(num)" + String(repeating: "x", count: Int.random(in: 0..<5))
}
@State var width: CGFloat = 100
var pill: some View { RoundedRectangle(cornerRadius: 5).fill(Color.gray) }
var scrollViewExample: some View {
ScrollView(.vertical) {
VStack {
sample.background(Color.red)
sample.background(Color.green)
}
}
}
var sample: some View {
return CollectionView(data: Array(0..<self.items.count), content: { el in
Text(self.items[el])
.padding(10)
.background(pill)
}).padding(10)
}
var simpleExample: some View {
GeometryReader { proxy in
VStack {
HStack {
Rectangle().fill(Color.red).frame(width: self.width)
Spacer().frame(width: 20)
sample
}
Slider(value: self.$width.animation(), in: 0...proxy.size.width)
}
}
}
var body: some View {
// simpleExample
scrollViewExample
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@tom-biel
Copy link

tom-biel commented Oct 28, 2019

if you change the UIOffset to NSSize(or UIOffset equivalent) it will also work on macOS

@mickspecial
Copy link

mickspecial commented Dec 1, 2019

Just what I needed to get my cell tags to flow to next line

@smarkars
Copy link

When I have more elements it grows on both top and bottom out of the container. Is it possible to make it only grow towards the bottom?

@chriseidhof
Copy link
Author

@smarkars I'm not sure if I understand the problem =) seems like a layout problem?

@zef
Copy link

zef commented Jan 16, 2020

Thanks for this! Definitely helped me understand some things about GeometryReader and PreferenceKey. For anyone else looking... I have my own version of this with a different approach here.

I was having some trouble with the frame of CollectionView being incorrect.

@cmhartman
Copy link

Great code, elucidated a lot of issues in swiftui. I had some code in xcode 11.1 where this was embedded in a scrollview and it worked great. However, similar to @zef, on update to 11.3 I started getting the error, Bound preference WidthPreferenceKey tried to update multiple times per frame and all of my views just stacked on top of each other. I tried to pull the the onpreferencekeychange out of the scrollview, and that got the layout working, but I started having the frame issues mentioned above. Any thoughts on what might have changed?

@andrewjmeier
Copy link

Hi @chriseidhof this is really cool! I noticed that if you put two CollectionViews together inside of a ScrollView they overlap. Do you have any advice?

        ScrollView {
            VStack {
                CollectionView(data: sentence.words) { word in
                    Text(word)
                }
                
                CollectionView(data: sentence.words) { word in
                    Text(word)
                }
            }
        }

@chriseidhof
Copy link
Author

Hi @andrewjmeier.

The issue is that the outermost view of the CollectionView is a GeometryReader. This blindly accepts the proposed width and height. A scroll view proposes a nil width and height for each axis it can scroll. The GeometryReader then becomes the default size (10x10).

When you explicitly set the .vertical axis on the ScrollView, the GR will receive the correct width, but still become 10 points high. But, given the correct width, we can calculate the height. We then can propagate this height up and add a frame around the GR with the explicit height.

I've update the sample code and fixed some other minor things as well. Let me know if you have further questions.

@vanwagonet
Copy link

The actual flow layout can be accomplished much more simply. See an alternative approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment