0
votes

I am trying to display images stored in an array which I am providing as a collection to ForEach and giving it a HStack view to display the result. But for life of me, can't fathom why HStack is returning a "VStack" sort of view?

Code:

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
}

I have stripped the code to barebones to highlight the issue and have attached my output screenshot for clarity. Please help.

output.

1

1 Answers

2
votes

The problem is the HStack being inside the ForEach. You are not aligning every view in an HStack, but just each separate view in its own HStack. It seems that by default SwiftUI prefers a vertical layout.

Consider this incorrect code:

struct ContentView: View {
    
    var body: some View {
        ForEach(1 ..< 10) { row in
            HStack {
                Text(String(row))
            }
        }
    }
}

And this correct code:

struct ContentView: View {
    
    var body: some View {
        HStack {
            ForEach(1 ..< 10) { row in
                Text(String(row))
            }
        }
    }
}

These are the results. Left is HStack inside the ForEach, and right is HStack outside the ForEach:

HStack inside ForEach HStack outside ForEach