SwiftUI layout issue with Vstack without giving child view a fix frame height

Viewed 188

I'm having issues trying to get my view to layout properly in the VStack when I add a Text view into the PartnerCarouselView VStack.

So, before adding the Text view, the code looks like this and it renders fine.

ContentView

import SwiftUI

struct ContentView: View {
    let items = 1...10

    let rows = [
        GridItem()
    ]

    var body: some View {
        ScrollView {
            VStack {
                PartnerCarouselView()
                PartnerCarouselView()
                PartnerCarouselView()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
import SwiftUI

struct PartnerCarouselView: View {

    let items = 1...10

    let rows = [
        GridItem()
    ]

    var body: some View {
        VStack {
            ScrollView(.horizontal, showsIndicators: false) {
                LazyHGrid(rows: rows, alignment: .top, spacing: 10) {
                    ForEach(items, id: \.self) { item in
                        PartnerCarouselItemView()
                    }
                }
            }
        }
    }
}

struct PartnerCarouselView_Previews: PreviewProvider {
    static var previews: some View {
        PartnerCarouselView()
    }
}

However, when I update my PartnerCarouselView to include a Text view like below …

    var body: some View {
        VStack {
            Text("Title")
            ScrollView(.horizontal, showsIndicators: false) {
                LazyHGrid(rows: rows, alignment: .top, spacing: 10) {
                    ForEach(items, id: \.self) { item in
                        PartnerCarouselItemView()
                    }
                }
            }
        }
    }

… the whole view gets really messed up with views overlapping each other:

overlapping view

So far, I've understood that if I gave each of the view a fixed frame as below …

    VStack {
        Text("Title").frame(height: 21)
        ScrollView(.horizontal, showsIndicators: false) {
            LazyHGrid(rows: rows, alignment: .top, spacing: 10) {
                ForEach(items, id: \.self) { item in
                    PartnerCarouselItemView()
                }
            }.frame(height: 350)
        }.frame(height: 350)
    }

… the view will layout fine. But I want my views to size dynamically, which is why I didn't provide any fixed height frame. Is there any way I can ensure all the child views in the VStack layout properly, without giving a fixed height frame?

0 Answers
Related