Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...