繁体   English   中英

如何验证在 SwiftUI 中单击按钮时动态添加的文本字段?

[英]How do I validate dynamically added textFields on a button click in SwiftUI?

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

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 中实现这一点?

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

这是可能的演示解决方案。

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

在此处输入图像描述

您可以有一个按钮来检查输入,如果正确,则将一些@State变量(如correct )设置为true

例子:

struct ContentView: View {
    var body: some View {
        InputView(correctInput: 5)
    }
}

struct InputView: View {
    @State private var input = ""
    @State private var correct = false
    let correctInput: Int
    
    var body: some View {
        VStack {
            TextField("?", text: $input)
                .foregroundColor(correct ? .green : .red)
            
            Button("Check answer") {
                correct = Int(input) == correctInput
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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