Dynamically Create TextFields in SwiftUI

Viewed 69

I'm trying to dynamically create Views, specifically TextField. I want to have a button that when pressed asks for user input and then creates a new TextField on the screen. The way I thought to accomplish this was to have an alert show when a button is pressed, ask for the user input there and then create the TextField when they submit. In my code, I want the "Add Workout" action to do this but I'm not sure how. If there are any suggestions on easier/more efficient ways please let me know.

Button("Add Workouts"){
            showingAlert = true
        }
        .alert("Workouts",isPresented:$showingAlert, actions:{
            TextField("Workout", text:$workoutText)
                .foregroundColor(.black)
            Button("Add Workout",action:{})
            Button("Cancel", role: .cancel,action:{})
        }, message:{
            Text("Please add a workout")
        })

Below I attached the 1st photo which is the current alert screen I have and the second photo which is what I'm expecting.

Alert Screen

Expected Outcome.

Eventually, I want to have the TextField stored as a Text so they have to press an edit button to edit the actual text but not my first priority currently.

1 Answers

You shoudn´t store UI Elements. Instead store the data you want to present. Consider this approach:

struct WorkoutView: View {
    
    @State private var showingAlert = false
    @State private var workoutTexts = [String]()
    @State private var workoutText: String = ""
    
    var body: some View {
            VStack{
                ScrollView{
                    VStack{
                        ForEach($workoutTexts, id: \.self){ $text in
                            TextField("", text: $text)
                                .font(.headline)
                        }
                    }
                }
                
                Button("Add Workouts"){
                            showingAlert = true
                        }
                        .alert("Workouts",isPresented:$showingAlert, actions:{
                            TextField("Workout", text:$workoutText)
                                .textFieldStyle(.roundedBorder)
                                .foregroundColor(.black)
                            Button("Add Workout",action:{
                                workoutTexts.append(workoutText)
                                workoutText = ""
                            })
                            Button("Cancel", role: .cancel,action:{})
                        }, message:{
                            Text("Please add a workout")
                        })
            }.padding()
    }
}

Showing an alert with TextField works only in IOS 16 and above.

Related