英文:
SwiftUI show collection of images
问题
我想展示一个类似于 UICollectionView
的图像网格,如下所示:
每种颜色代表一张图片。
当我执行以下操作时:
struct ContentView: View {
var body: some View {
ScrollView{
ForEach(0..<8) { i in
HStack {
ForEach(0..<3) { j in
ZStack(alignment: .center) {
Image("image")
.background(Color.random)
.clipped()
.aspectRatio(contentMode: .fill)
}
.frame(width: 120, height: 120)
.background(Color.random)
}
}
}
}
}
}
我得到了一张图片,它没有受到其框架的限制,因此填满整个屏幕。
英文:
I would like to show a grid of images similar to UICollectionView
like this:
With each color representing an image.
When I do the following:
struct ContentView: View {
var body: some View {
ScrollView{
ForEach(0..<8) { i in
HStack {
ForEach(0..<3) { j in
ZStack(alignment: .center) {
Image("image")
.background(Color.random)
.clipped()
.aspectRatio(contentMode: .fill)
}
.frame(width: 120, height: 120)
.background(Color.random)
}
}
}
}
}
}
I get one image which is not bound by its frame and therefore fills the whole screen.
答案1
得分: 1
将图像设置为具有帧和可调整大小的修饰符。
Image("image")
.resizable()
.frame(width: 120, height: 120)
完整示例
struct ContentView: View {
var body: some View {
ScrollView{
ForEach(0..<8) { i in
HStack {
ForEach(0..<3) { j in
ZStack(alignment: .center) {
Image("image")
.resizable()
.frame(width: 120, height: 120)
}
.frame(width: 120, height: 120)
.background(Color.blue)
}
}
}
}
}
}
英文:
Set a frame and resizable modifier to you image.
Image("image")
.resizable()
.frame(width: 120, height: 120)
Full example
struct ContentView: View {
var body: some View {
ScrollView{
ForEach(0..<8) { i in
HStack {
ForEach(0..<3) { j in
ZStack(alignment: .center) {
Image("image")
.resizable()
.frame(width: 120, height: 120)
}
.frame(width: 120, height: 120)
.background(Color.blue)
}
}
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论