如何根据父视图中的可用空间制作列数可变的 SwiftUI 网格?

Rub*_*ube 5 ios swift swiftui

我正在使用 SwiftUI 开发 iOS-iPadOS 应用程序。我有一组图像,我想以不同的行大小显示(所有行必须等长)填充大部分父视图(边到边列表单元格)。如果您知道需要多少列或行,这样做非常简单。相反,我想要与设备无关的适应性代码。尺寸类别(常规和紧凑型)不是一种选择,因为 iPad 分屏和 iPhone 横向尺寸紧凑但水平空间很大。

我寻找了一种获取视图大小的方法,尽管我认为这不是一个好方法。我什么也没发现。

这是我在构建布局时使用的基本代码(仍然不适应接受表的行数或列数):

VStack(alignment: .center){
    HStack(alignment: .center){
        Spacer()
        ForEach(lista.prefix(5)) { periodo in
            Group{
            Image(systemName:"\(periodo.imagen).circle.fill")
            .resizable()
            .foregroundColor(color(periodo.color))
            .frame(width: 55, height: 55)
            .onTapGesture {
                self.periodoActual = self.lista.firstIndex(of: periodo) ?? 0
            }
            Spacer()
            }
        }
    }
    HStack(alignment: .center, spacing: 10){
        ForEach(lista.dropFirst(5)) { periodo in
            Image(systemName:"\(periodo.imagen).circle.fill")
            .resizable()
            .foregroundColor(color(periodo.color))
            .frame(width: 55, height: 55)
            .onTapGesture {
                self.periodoActual = self.lista.firstIndex(of: periodo) ?? 0
            }
        }
    }
}.frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity)
Run Code Online (Sandbox Code Playgroud)

其中 lista 是一个数组(其长度为 10),其中包含从 JSON 文件解码的自定义结构的实例。periodoActual 是一个状态变量(@State)。

有人有一个有效解决这个问题的想法吗?提前致谢。