如何在 SwiftUI 中单击按钮时验证动态添加的 textFields? [英] How do I validate dynamically added textFields on a button click in SwiftUI?

查看:21
本文介绍了如何在 SwiftUI 中单击按钮时验证动态添加的 textFields?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 InputView 结构,并在另一个视图的 foreach 循环中动态添加这些 InputView:

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
}
}

到此为止立即显示输入是否正确.但是,我想添加一个按钮,以便所有 InputViews 的输入仅在单击时进行验证.如何在 SwiftUI 中实现这一点?

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?

推荐答案

您可以通过制作文本字段模型并为轨道的每个 InputView 使用一个 isValid 标志来完成此操作.

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) })
            }
        }
    }
}

这篇关于如何在 SwiftUI 中单击按钮时验证动态添加的 textFields?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆