49 lines
1.3 KiB
Swift
49 lines
1.3 KiB
Swift
//
|
|
// AspectVGrid.swift
|
|
// Memorize
|
|
//
|
|
// Created by ching on 2023/2/13.
|
|
//
|
|
|
|
import SwiftUI
|
|
|
|
struct AspectVGrid<Item, ItemView>: View where ItemView: View, Item: Identifiable {
|
|
var items: [Item]
|
|
var aspectRatio: CGFloat
|
|
var content: (Item) -> ItemView
|
|
var body: some View {
|
|
let width: CGFloat = 100
|
|
LazyVGrid(columns: [GridItem(.adaptive(minimum: width))]) {
|
|
ForEach(items) {
|
|
item in content(item).aspectRatio(aspectRatio, contentMode: .fit)
|
|
}
|
|
}
|
|
}
|
|
|
|
private func widthThatFits(itemCount: Int, in size: CGSize, itemAspectRatio: CGFloat) -> CGFloat {
|
|
var columCount = 1
|
|
var rowCount = itemCount
|
|
|
|
repeat {
|
|
let itemWidth = size.width / CGFloat(columCount)
|
|
let itemHeight = itemWidth / itemAspectRatio
|
|
if CGFloat(rowCount) * itemHeight < size.height {
|
|
break
|
|
}
|
|
columCount += 1
|
|
rowCount = (itemCount + columCount - 1) / columCount
|
|
} while columCount < itemCount
|
|
|
|
if columCount > itemCount {
|
|
columCount = itemCount
|
|
}
|
|
return floor(size.width / CGFloat(columCount))
|
|
}
|
|
}
|
|
|
|
// struct AspectVGrid_Previews: PreviewProvider {
|
|
// static var previews: some View {
|
|
// AspectVGrid()
|
|
// }
|
|
// }
|