diniska / swiftui-wrapping-stack

A SwiftUI Views for wrapping HStack elements into multiple lines
MIT License
84 stars 20 forks source link

SwiftUI WrappingStack

Swift 5.3 Xcode 12.5+ iOS 9.0+ iPadOS 9.0+ MacOS 10.10+ Build & Test codebeat badge

A SwiftUI Views for wrapping HStack elements into multiple lines.

List of supported views

How to use

Step 1

Add a dependency using Swift Package Manager to your project: https://github.com/diniska/swiftui-wrapping-stack

Step 2

Import the dependency

import WrappingStack

Step 3

Replace HStack with WrappingHStack in your view structure. It is compatible with ForEach.

struct MyView: View {

    let elements = ["Cat 🐱", "Dog 🐢", "Sun 🌞", "Moon πŸŒ•", "Tree 🌳"]

    var body: some View {
        WrappingHStack(id: \.self) { // use the same id is in the `ForEach` below
            ForEach(elements, id: \.self) { element in
                Text(element)
                    .padding()
                    .background(Color.gray)
                    .cornerRadius(6)
            }
        }
        .frame(width: 300) // limiting the width for demo purpose. This line is not needed in real code
    }

}

The result of the code above:

WrappingHStack for macOS

Customization

Customize appearance using the next parameters. All the default SwiftUI modifiers can be applied as well.

WrappingHStack parameters

Parameter name Description
alignment horizontal and vertical alignment. .center is used by default. Vertical alignment is applied to every row
horizontalSpacing horizontal spacing between elements
verticalSpacing vertical spacing between the lines

Performance considerations

The code written in a way to cache the elements representing views sizes, it doesn't re-calculate the size for different views with the same id.