我有一个使用LazyVGrid的“画廊”,
struct ContentView: View {
@State private var results = [Result]()
let columns = [
GridItem(.flexible(), spacing: 1),
GridItem(.flexible(), spacing: 1),
GridItem(.flexible(), spacing: 1),
]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 1) {
ForEach(results, id: \.self) { result in
AsyncImage(url: URL(string: result.urls.small)) { image in
image
.resizable()
.aspectRatio(1, contentMode: .fit)
}
}
}
}
}无论我指定什么参数
.aspectRatio(1, contentMode: .fit)“适合”和“填充”都会导致图像“拉伸”,即不尊重它们的纵横比。他们想要的是尊重他们的纵横比,填满整个空间。请看下面的图片,它们现在的样子

发布于 2022-06-16 06:05:29
是的,没错,需要正方形的单元格
在这种情况下,我们需要在网格时间内给出一个保持所需方形形状的容器,并用具有自身方面(独立于网格)的图像填充该容器。
下面是一个可能的解决方案,用Xcode 13.4 / iOS 15.5进行测试

主要部分:
ForEach(results, id: \.self) { result in
Color.clear.overlay(
AsyncImage(url: URL(string: result)) { phase in
switch phase {
case .success(let image):
image
.resizable()
.scaledToFill() // << for image !!
default:
Image(systemName: "photo")
}
}
)
.frame(maxWidth: .infinity)
.aspectRatio(1, contentMode: .fit) // << for square !!
.clipped()
}https://stackoverflow.com/questions/72640943
复制相似问题