我试图显示存储在数组中的图像,我将其作为集合提供给ForEach,并给它一个HStack视图来显示结果。但对于我的一生,不知道为什么HStack要返回一个"VStack“的那种观点?
代码:
import SwiftUI
struct ContentView: View {
var body: some View {
Home()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Home: View {
// 40 = padding horizontal
// 60 = 2 card to right side...
var width = UIScreen.main.bounds.width - (40 + 60)
var height = UIScreen.main.bounds.height/2
var books = [
Book(id: 0, image: "p1", offset: 0),
Book(id: 1, image: "p0", offset: 0),
Book(id: 2, image: "p3", offset: 0),
Book(id: 3, image: "p2", offset: 0),
Book(id: 4, image: "p5", offset: 0),
Book(id: 5, image: "p4", offset: 0),
]
var body: some View{
ForEach(books.reversed()) { book in
HStack{
Image(book.image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: width, height:getheight(index: book.id))
.cornerRadius(25)
.shadow(color: Color.black.opacity(0.5), radius: 5, x: 5)
}
}
}
func getheight(index: Int)->CGFloat{
return height - (index < 3 ? CGFloat(index) * 40 : 80)
}
}
struct Book : Identifiable {
var id: Int
var image : String
var offset : CGFloat
}为了突出这个问题,我已经将代码剥离为基本代码,并且为了清晰起见,我还附加了输出屏幕截图。请帮帮忙。

。
发布于 2020-10-22 21:06:09
问题是HStack在ForEach中。您并不是对齐HStack中的每个视图,而是在它自己的HStack中对每个单独的视图。在默认情况下,SwiftUI似乎更喜欢垂直布局。
考虑以下不正确的代码:
struct ContentView: View {
var body: some View {
ForEach(1 ..< 10) { row in
HStack {
Text(String(row))
}
}
}
}这是正确的代码:
struct ContentView: View {
var body: some View {
HStack {
ForEach(1 ..< 10) { row in
Text(String(row))
}
}
}
}这些都是结果。左边是HStack is ForEach,右边是HStack 在 ForEach


https://stackoverflow.com/questions/64489999
复制相似问题