我對 Swift 比較陌生,并且有一個網格布局問題:我目前正在使用帶有自適應網格專案和單列的 LazyHGrid 來靈活地布局專案,而無需預先確定的列數。我通過根據要顯示的專案數設定 maxWidth 網格布局和 maxWidth 來確定顯示的列數
我在下面的每個場景中試圖完成的(使用一個也可以擴展的解決方案)基本上是通過將專案從位置“??”移到位置“??”來調整下面示例中的位置,消除“浮動孤兒”專案不擁抱邊緣。“??”位置已經正確。
約束
- 我想最小化此網格使用的寬度,但并非所有行都可以容納更高的堆疊(因此設定一堆脆弱的規則似乎是一個糟糕的解決方案)而且我對設定固定的行專案高度不感興趣以洗掉需要動態解決方案
- 我想避免使用嵌套的 HStack 和 VStack 手動創建網格并撰寫一堆額外的邏輯來管理給定父行高度的每一行和列的內容(通過 GeometryReader 檢索)。
我的嘗試
- 我查看了 Lazy_Grid 檔案,看看是否有一個視圖修飾符可以實作這一點——沒有遇到過(盡管我完全有可能錯過了它!)
- 我想也許翻轉 layoutDirection(從 LTR 到 RTL)可能會做到,但沒有這樣的運氣
- 我改變了重復的 gridItem 和 lazyHGrid 容器的對齊值,但浮動孤兒仍然存在
例子
- 對于三個專案:
/* short */
___________
????|
????|
/* tall */
___________
??|
??|
??|
- 對于四個專案:
/* short */
___________
????|
????|
/* tall */
___________ ___________
????| ????| // NOTE: I *could* constrain the height in this case
????| ????| // to achieve the 2x2 grid but would rather not
????|
- 對于五個專案:
/* short */
___________
??????|
??????|
/* tall */
___________
????|
????|
????|
- 對于六個專案:
/* short */
___________
??????|
??????|
/* tall */
___________
????|
????|
????|
- 對于七個專案:
/* short */
___________
????????|
????????|
/* tall */
___________
????|
????|
????|
????|
let items = filterItems()
let iconCount = CGFloat(items.count)
let iconSize: CGFloat = 18
let spacing: CGFloat = 2
// NOTE: `iconCount / 2` because the min-height of the parent
// only fits two items. The current item count is 7 and it's
// unlikely that it'd ever do more than double.
let cols = CGFloat(iconCount / 2).rounded(.up)
let maxWidth = calcWidth(for: cols, iconSize: iconSize, spacing: spacing)
let minWidth = cols < 2 ? maxWidth : calcWidth(for: cols - 1, iconSize: iconSize, spacing: spacing)
LazyHGrid(
rows: Array(
repeating: GridItem(
.adaptive(minimum: iconSize, maximum: iconSize),
spacing: spacing,
alignment: .center
),
count: 1
),
alignment: .center,
spacing: spacing
) {
ForEach(0..<items.count, id: \.self) { n in
...item views...
}
}
.frame(minWidth: minWidth, maxWidth: maxWidth)
我的大腦一直在尋找類似于 CSS 的 FlexBox 的 Swift 概念,
原答案:
這不是理想的解決方案,但一種選擇是使用 3D 旋轉來翻轉 Y 軸上的布局。我在 Playgrounds 中使用了一個簡單的文本視圖作為示例:
LazyHGrid(
rows: Array(
repeating: GridItem(
.adaptive(minimum: iconSize, maximum: iconSize),
spacing: spacing,
alignment: .center
),
count: 1
),
alignment: .center,
spacing: spacing
) {
ForEach(0..<Int(iconCount), id: \.self) { n in
Text("B")
.frame(width: iconSize, height: iconSize)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
}
}
.frame(minWidth: minWidth, maxWidth: maxWidth)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/349779.html
