Search code examples
swiftuihstack

SwiftUi line pass with a hstack


Hello to all, I have a simple question yet I find not that solutions that seems very complex.

I am looking for a way to make a line break on my Hstack once the screen size is exceeded.

Here is my code:

//
//  TrendySection.swift
//  Activiteam
//
//  Created by Theo Marie on 30/04/2022.
//
struct IdentifiableSport: Identifiable {
    var id = UUID()
    var name: String
    var icon: String
}


import SwiftUI
struct TrendySection: View {
    var body: some View {
        let trendySports = [
            IdentifiableSport(name: "Tennis", icon: "tennis"),
            IdentifiableSport(name: "Badminton", icon: "badminton"),
            IdentifiableSport(name: "Basketball", icon: "basketball"),
            IdentifiableSport(name: "Football", icon: "football"),
            ]
        VStack(spacing: 12) {
            
        Text("Activités les plus recherchées")
          .font(Font.custom("Poppins-Bold", size: 24))
          .foregroundColor(Color.black)
          .frame(maxWidth: 300, alignment: .topLeading)
          .lineLimit(2)
                HStack(spacing: 32) {
                    ForEach(trendySports) { trendySport in
                        Trendybutton(icon: trendySport.icon, sportName: trendySport.name)
                               }
                }

                  .padding([.top, .bottom, .leading, .trailing], 0)
            }
    }
}

struct TrendySection_Previews: PreviewProvider {
    static var previews: some View {
        TrendySection()
    }
}

My current rendering

the Figma model

I thank you in advance for your proposal.


Solution

  • As someone suggested, you should try to checkout LazyVStack or LazyHStack. Here is some code that may help you.

    struct ContentView: View {
        
        let items = [GridItem(.flexible()), GridItem(.flexible()),GridItem(.flexible())]
        
        let data = (1...20).map { "Item #\($0)" }
        
        var body: some View {
            LazyVGrid(columns: items) {
                ForEach(data, id: \.self) { item in
                    Text(item)
                        .padding()
                        .background(.green)
                }
            }
        }
    }
    

    enter image description here