Home > Enterprise >  How to add elements to a HStack Using ForEach SwiftUi
How to add elements to a HStack Using ForEach SwiftUi

Time:10-10

Im fairly new to Swift and I'm trying to produce a HStack (that will be used in a progress bar) of element and to be able to add elements with a button. Im not sure if I should use a variable in the ForEach(1..<Variable) section or use another method. Here is the code I have so far but it did not work.

struct ContentView: View {
@State var fill : CGFloat = 0

@State var NumberOfCircles : Int = 0 var body: some View {

            HStack(spacing:100) {

                ForEach(0..<NumberOfCircles){ _ in
                   MyShape()

}

        Button(action: {NumberOfCircles = 5}, label: {
            Text("Button")
            
        })
        
    }

CodePudding user response:

ForEach in SwiftUI needs a constant range to loop over. However, as the error suggests, if you conform to Identifiable or use ForEach(_:id:content:) and provide an explicit id it is happy. So try this:

struct ContentView: View {
    @State var fill: CGFloat = 0
    @State var NumberOfCircles: Int = 0
    
    var body: some View {
        
        HStack(spacing: 20) {
            ForEach(0..<NumberOfCircles, id: \.self){ _ in // <-- here
                MyShape()
            }
            Button(action: {NumberOfCircles = 5}){
                Text("Button")
            }
        }
    }

}

CodePudding user response:

I'm not sure what's your problem, but I tested this code and it works:

struct ContentView: View {
    @State var numberOfCircles = 1
    var body: some View {
        VStack {
            HStack {
                ForEach(0..<numberOfCircles, id:\.self) { _ in
                    Circle()
                        .frame(width: 30, height: 30)
                }
            }
            Button { numberOfCircles = 5 } label: {
            Text("Add Circles")
        }
            
        }
    }
}

Btw, naming convention for variables in Swift is camelCase. That means that declaring a variable you should name it numberOfCircles , not NumberOfCircles . The first uppercase letter is reserved for naming Classes, Structs and Protocols.

  • Related