โจItemsView
Last updated
Last updated
SwiftUI โฉ Layout โฉ Grids โฉ examples โฉ ItemsView โฉ
โฌ๏ธ ้่ฆ๏ผ arr.index(of:)
import SwiftUI
struct ItemsView<
Item : Identifiable,
L : IndexedGridLayout, // IndexedGridLayout
ItemView: View
>: View
{
let items: [Item]
// โญ inject layout
let layout: (CGSize) -> L
// โญ inject view builder
@ViewBuilder let itemView: (Item) -> ItemView
var body: some View {
GeometryReader { geo in
ForEach(items) { item in
let i = items.index(of: item)! // ๐ Array+ .index(of:)
let layout = layout(geo.size) // โญ injected layout
let size = layout.cellSize
itemView(item)
.frame(width: size.width, height: size.height)
.position(layout.cellCenter(at: i))
}
}
}
}
// ----------------
// Previews
// ----------------
struct ItemsView_Previews: PreviewProvider {
static var previews: some View {
ItemsView(
items: Array(1...25)
) { size in // โญ inject layout instance
RatioRetainingLayout(
1, count: 20, in: size
)
} itemView: { i in // โญ inject view builder
Color(hue: 0.6, saturation: 0.8, brightness: 0.5)
.padding(1)
.overlay { Text("\(i)").shadow(radius: 2) }
}
.preferredColorScheme(.dark)
}
}
supporting files: