Creating controls at runtime in SwiftUI

Viewed 164

The following code creates new controls every time a button is pressed at runtime, the problem is that the picker selection is set to the same state.

How can I create new controls with different state variables so they can operate separately ?

struct ContentView: View {

   @State private var numberOfControlls = 0
   @State var selection: String="1"
    
    var body: some View {

        
        
      VStack {
          Button(action: {
              self.numberOfControlls += 1
          }) {
              Text("Tap to add")
          }

          ForEach(0 ..< numberOfControlls, id: \.self) { _ in
            
            Picker(selection: self.$selection, label: 
                Text("Picker") {

                Text("1").tag(1)
                Text("2").tag(2)
             }

         
          }
       }
        
    }
}
1 Answers

How can I create new controls with different state variables so they can operate separately ?

Separate control into standalone view with own state (or view model if/when needed).

Here is a demo:

struct ContentView: View {

   @State private var numberOfControlls = 0

    var body: some View {
      VStack {
          Button(action: {
              self.numberOfControlls += 1
          }) {
              Text("Tap to add")
          }

          ForEach(0 ..< numberOfControlls, id: \.self) { _ in
            ControlView()
          }
       }
    }
}

struct ControlView: View {
   @State var selection: String="1"
    var body: some View {
        Picker(selection: self.$selection, label:
            Text("Picker")) {

            Text("1").tag(1)
            Text("2").tag(2)
         }
    }
}
Related