问题描述
我正在尝试制作一个包含 x 个图像的 HStack,并将以包装 HStack 的方式显示它们(即,如果 7 个图像中只有 4 个适合该行,则将剩余的 3 个溢出到下一行).
我正在尝试使用库 WrappingHStack (
I am trying to make a HStack which contains x number of images and will display them in a wrapping HStack manner (i.e if only 4 of the 7 images fit on the line, then spill the 3 remaining over onto the next line).
I am trying to use the library WrappingHStack (https://github.com/dkk/WrappingHStack) but the result isn't as expected, the images are not wrapping around.
Here is my code:
@State var numEarths : Int = 7;
var body: some View {
VStack{
Text("If everyone were to live like you, we would need \(numEarths) Earths").font(.title)
WrappingHStack{
ForEach(0 ..< numEarths){_ in
Image("logo")
}
}
}
}
Here is the result on the simulator (see, no wrapping)...we should see 7 Earth logo images but you can only see 4 (and a tiny bit of number 5).screenshot of image
Please can someone help me fix this issue? I am new to SwiftUI dev so please go lightly on me if this is a silly mistake. Thanks.
According to the WrappingHStack
library, if you want to achieve what you above-mentioned, you need to do two things:
- Give your
Image
aframe
so that theWrappingHStack
can know how many elements to put in per line. - Change your
ForEach
loop toWrappingHStack
, becauseWrappingHStack
can be used as aForEach
to loop over items.
WrappingHStack(0..<numEarths, id:\.self) { _ in
Image("logo")
.resizable()
.frame(width: 100, height: 100)
}
这篇关于SwiftUI 用图像包装 HStack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!