SwiftUI WrappingStack

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

用于将 HStack 元素包装成多行的 SwiftUI 视图。

支持的视图列表

如何使用

步骤 1

使用 Swift Package Manager 将依赖项添加到您的项目中: https://github.com/diniska/swiftui-wrapping-stack

步骤 2

导入依赖项

import WrappingStack

步骤 3

在您的视图结构中将 HStack 替换为 WrappingHStack。它与 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
    }
    
}

以上代码的结果

WrappingHStack for macOS

自定义

使用以下参数自定义外观。所有默认的 SwiftUI 修饰符也可以应用。

WrappingHStack 参数

参数名 描述
alignment 水平和垂直对齐。默认使用 .center。垂直对齐应用于每一行
horizontalSpacing 元素之间的水平间距
verticalSpacing 行之间的垂直间距

性能注意事项

代码编写方式旨在缓存表示视图大小的元素,它不会为具有相同 id 的不同视图重新计算大小。