简体   繁体   中英

SwiftUI dynamically add/remove TextField with Stepper

Hi all I'm new to SwiftUI and am trying to find a neat way to add or remove TextFields when either the plus or minus of a steeper is pressed.

I currently have

@State private var answers: [String] = ["", ""]
Stepper(onIncrement: {
    if(numberOfAnswers < 10){
        answers.append("")
        numberOfAnswers += 1
    }
    },
    onDecrement: {
        if(numberOfAnswers > 2){
        answers.removeLast()
        numberOfAnswers -= 1
        }
    }) {
ForEach(answers.indices, id: \.self) { index in
    TextField("Answer", text: $answers[index])
}

However this results in an Index out of bounds exception when onDecrement is called. I have tried wrapping the String to conform to Identifiable (with the @State inside the struct declaration), using ForEach(answers) however this produces a warning stating that the variable will not be updated.

I have tried solutions posted here but to no avail.

I do not need to persistently store the result of this, as it will be passed to a separate function making an API call on button press.

Any help for this would be much appreciated.

Here is fixed replicated code. Tested with Xcode 11.4 / iOS 13.4

struct DemoView: View {
    @State var numberOfAnswers = 2
    @State private var answers: [String] = ["", ""]

    var body: some View {
        Stepper(onIncrement: {
            if(self.numberOfAnswers < 10){
                self.answers.append("")
                self.numberOfAnswers += 1
            }
        },
                onDecrement: {
                    if(self.numberOfAnswers > 2){
                        self.answers.removeLast()
                        self.numberOfAnswers -= 1
                    }
        }) {
            ForEach(Array(answers.enumerated()), id: \.0) { i, _ in
                TextField("Answer", text: self.$answers[i])
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM