A SwiftUI component that arranges child views in a horizontal flow layout, automatically wrapping to new lines when the container width is exceeded. Each item in the flow layout takes its natural size based on its content.
- Horizontal flow layout with automatic line wrapping
- Each item sizes to fit its content
- Customizable spacing between items
- Support for various types of child views
- Built with SwiftUI ViewBuilder
- Efficient layout calculation
- Compatible with iOS 16.0 and newer
Add the following dependency to your Package.swift file:
.package(url: "https://github.com/yourusername/HorizontalFlowLayout.git", from: "1.0.0")Or add it directly through Xcode:
- File > Swift Packages > Add Package Dependency
- Enter the repository URL:
https://github.com/yourusername/HorizontalFlowLayout.git - Select the version you want to install
- Add the package to your target
HorizontalFlowLayout is very easy to use and provides multiple ways to create layouts:
import SwiftUI
import HorizontalFlowLayout
struct ContentView: View {
// Define an identifiable data model
struct Tag: Identifiable {
let id = UUID()
let name: String
}
// Your data collection
let tags = [
Tag(name: "SwiftUI"),
Tag(name: "Layout"),
Tag(name: "Flow"),
Tag(name: "Horizontal")
]
var body: some View {
HorizontalFlowLayout(tags, spacing: 8) { tag in
Text(tag.name)
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(Color.blue.opacity(0.2))
.cornerRadius(8)
}
.padding()
}
}If you need to use a variety of different views rather than a homogeneous collection, use the ViewFlowLayout:
ViewFlowLayout(spacing: 8) {
Text("First item")
Image(systemName: "star")
Label("Labeled item", systemImage: "tag")
Circle().frame(width: 40, height: 40)
}HorizontalFlowLayout(
myItems,
spacing: 12,
alignment: .center
) { item in
// Your view here
}For a complete example, check out the HorizontalFlowLayoutExampleView included in the package:
import SwiftUI
import HorizontalFlowLayout
struct MyView: View {
var body: some View {
HorizontalFlowLayoutExampleView()
}
}The layout works by:
- Measuring the container width
- Measuring each child view's size
- Calculating positions for each view
- Positioning items in rows, wrapping to a new line when needed
- iOS 16.0+ / macOS 13.0+
- Swift 6.0+
- Xcode 15.0+
HorizontalFlowLayout is available under the MIT license. See the LICENSE file for more info.