【问题标题】:HStack returning "VStack" viewHStack 返回“VStack”视图
【发布时间】:2020-10-22 20:23:00
【问题描述】:

我正在尝试显示存储在数组中的图像,该数组作为集合提供给 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
}

我已将代码剥离为准系统以突出显示该问题,并附上我的输出屏幕截图以便清楚起见。请帮忙。

.

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    问题在于HStackForEach 中。您不会对齐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 inside ForEach,右边是HStack outside ForEach:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-20
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多