Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
981 views
in Technique[技术] by (71.8m points)

swift - How do I validate dynamically added textFields on a button click in SwiftUI?

I have the following InputView struct and add those InputViews dynamically within a foreach loop in another view:

struct InputView: View {

@State private var input: String = ""
var correct_input: Int

var body: some View {
    TextField("?", text: $input)
        .foregroundColor(setColor())
}

func setColor() -> Color {
    
    if (Int(input) == correct_input) {
        return Color.green
    }
    return Color.red
}
}

Up to now it is shown immediately whether the input is correct. However, I would like to add a button so that the input of all InputViews is only validated when it is clicked. How can I achieve this in SwiftUI?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can be done this by making a model of text fields and use one isValid flag for each InputView for the track.

Here, is the possible demo solution.

struct TextFieldModel: Identifiable {
    var id = UUID()
    var input: String
    var correctInput: Int
    var isValidate: Bool = true
}

struct InputView: View {
    @Binding var input: TextFieldModel
    var body: some View {
        TextField("?", text: $input.input)
            .foregroundColor(input.isValidate ? Color.blue : Color.red)
    }
}

struct ContentViewTextFields: View {
    @State var arrTextFields: [TextFieldModel] = [
        .init(input: "", correctInput: 5),
        .init(input: "", correctInput: 10),
        .init(input: "", correctInput: 1)
    ]
    
    @State var isValidate: Bool = true
    
    var body: some View {
        VStack{
            ForEach(arrTextFields.indices) { index in
                InputView(input: $arrTextFields[index])
                    .background(Color.gray.opacity(0.2))
                    .padding()
            }
            Spacer()
            
            Button("Validate") {
                // Here validate all text
                arrTextFields.indices.forEach({arrTextFields[$0].isValidate = (Int(arrTextFields[$0].input) == arrTextFields[$0].correctInput) })
            }
        }
    }
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...