GridStack
1.0.0
Swiftui的灵活网格布局视图。
Apple在WWDC20上发布了LazyVGrid和LazyHGrid 。
如果您只能支持I(PAD)OS 14,MACOS 11,TVOS 14,WATCOS 7分别^--绝对是必经之路。
如果您想支持I(PAD)OS 13,MACOS 10.15,TVOS 13,WatchOS 6继续阅读。
iOS 13+, MacOS 10.15+, TVOS 13+, ⌚Watchos 6+
只需传递网格电池应具有的最小宽度和它们之间的间距,它将根据可用宽度进行调整。
所以写这个:

会给你这个:

当设备旋转时,它还可以正确调整:

想一想您希望细胞的最小宽度是什么。这样,很容易调整到任何可用空间。您需要提供的唯一其他尺寸是单元之间的间距。
要实际创建网格,我们需要知道项目的数量。然后,将使用每个索引和细胞宽来调用内容视图构建器,然后可以将其传递到内部显示的任何内容的框架。
网格将包装您提供的每个项目以将单元格设置为宽度的视图。小区没有高度约束。这样您就可以尽可能灵活地缩小内容。这只是您可以做的几个示例。
GridStack ( ... ) { index , cellWidth in
Text ( " ( index ) " )
// Don't pass any height to the frame to let it be defined by it's content
. frame ( width : cellWidth )
} GridStack ( ... ) { index , cellWidth in
Text ( " ( index ) " )
// Pass the cellWidth as width and height to the frame to make a square
. frame ( width : cellWidth , height : cellWidth )
} GridStack ( ... ) { index , cellWidth in
Text ( " ( index ) " )
// Pass the cellWidth as width and a portion of it as height to get a certain aspect ratio
. frame ( width : cellWidth , height : cellWidth * 0.75 )
} GridStack (
minCellWidth : Length ,
spacing : Length ,
numItems : Int ,
alignment : HorizontalAlignment = . leading ,
content : ( index : Int , cellWidth : CGFloat ) - > Void
) 我通过从John Susek撰写的Flowstack创建了GridStack 。