子类化TextField并在SwiftUI中将状态传递给它

子类化TextField并在SwiftUI中将状态传递给它,swift,swiftui,Swift,Swiftui,我正在尝试将TextField子类化,以清理代码。我目前在表单中有一个文本字段“row”,但最终我想找到一种方法使其可扩展(并且有更多的HStacks) 我不想重复HStack声明4次(行数)。所以我需要子类化。但是,我需要找到一种方法将状态(美元符号)传递给子类。怎么用?另外,是否有任何方法可以拥有一个状态数组,以便我可以使用ForEach?例如: var imaginaryArrayWithStates = [$textFieldValue1, $textFieldValue2] // yo

我正在尝试将
TextField
子类化,以清理代码。我目前在
表单中有一个文本字段“row”,但最终我想找到一种方法使其可扩展(并且有更多的
HStack
s)

我不想重复
HStack
声明4次(行数)。所以我需要子类化。但是,我需要找到一种方法将状态(美元符号)传递给子类。怎么用?另外,是否有任何方法可以拥有一个状态数组,以便我可以使用
ForEach
?例如:

var imaginaryArrayWithStates = [$textFieldValue1, $textFieldValue2] // you can't do this, but I would like to iterate states somehow...

// ...so that I can use a ForEach
ForEach(imaginaryArrayWithStates) { state
    MyCustomTextField() // how do I pass the state to this subclass? 
}

您可以使用
@Binding

struct CustomTextField: View {
    @Binding var value: String

    var body: some View {
        HStack {
            Text("Balance") // can be extracted as a variable
            TextField("", text: $value, onEditingChanged: { changing in
                print("Changing: \(changing)")
            }, onCommit: {
                print("Committed!")
            })
                .multilineTextAlignment(.trailing)
                .keyboardType(.numbersAndPunctuation)
                .onReceive(Just(value)) { newValue in
                    let filtered = newValue.filter { "0123456789".contains($0) }
                    if filtered != newValue {
                        self.value = filtered
                    }
                }
        }
    }
}

你所说的*子类化TextField
是什么意思
TextField`是struct。对不起,我的意思是创建一个包含
HStack
的视图。
struct CustomTextField: View {
    @Binding var value: String

    var body: some View {
        HStack {
            Text("Balance") // can be extracted as a variable
            TextField("", text: $value, onEditingChanged: { changing in
                print("Changing: \(changing)")
            }, onCommit: {
                print("Committed!")
            })
                .multilineTextAlignment(.trailing)
                .keyboardType(.numbersAndPunctuation)
                .onReceive(Just(value)) { newValue in
                    let filtered = newValue.filter { "0123456789".contains($0) }
                    if filtered != newValue {
                        self.value = filtered
                    }
                }
        }
    }
}
struct ContentView: View {
    @State var values = ["312", "222", ""]

    var body: some View {
        Form {
            Section {
                ForEach(values.indices, id: \.self) { index in
                    CustomTextField(value: self.$values[index])
                }
            }
        }
    }
}