HStack返回“ VStack”视图

时间:2020-10-22 20:23:00

标签: swiftui

我试图显示存储在数组中的图像,该数组作为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
}

我将代码剥离了出来,以突出显示该问题,并附上了我的输出屏幕截图,以使其更加清晰。请帮忙。

output

1 个答案:

答案 0 :(得分:2)

问题是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的内部{strong> {strong} ForEach,右侧为HStack的外部{strong} {strong} {strong}外部:

HStack inside ForEach HStack outside ForEach