0

I assume there must be a way you to use modifiers for every text field in a section without having to type them for each text field. Can the result of the example below be achieved with ForEach or something else that I'm not aware of?

            Section() {
                TextField("", text: $text1).keyboardType(.decimalPad).modifier(ClearButton(text: $text1))
                TextField("", text: $text2).keyboardType(.decimalPad).modifier(ClearButton(text: $text2))
                TextField("", text: $text3).keyboardType(.decimalPad).modifier(ClearButton(text: $text3))
                TextField("", text: $text4).modifier(ClearButton(text: $text4))
            }

1 Answers1

0

Here is possible approach. Tested with Xcode 11.4 / iOS 13.4

struct DemoSectionView: View {
    @State private var texts = Array(repeating: "", count: 4)
    var body: some View {
        Section() {
            ForEach(texts.indices, id: \.self) { i in
                DemoTextField(text: self.$texts[i],
                   keyboard: i == self.texts.count - 1  ? .default : .decimalPad)
            }
        }
    }
}

struct DemoTextField: View {
    @Binding var text: String
    var keyboard: UIKeyboardType = .default

    var body: some View {
        TextField("", text: $text)
           .keyboardType(keyboard)
           .modifier(ClearButton(text: $text))
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690