Ilja
Ilja

Reputation: 1215

dynamic binding in SwiftUI ForEach for a field

For an abstract input field that should be rendered in ForEach, given a struct,

struct InputFieldCustom: Identifiable, Hashable {

    let id = UUID()
    let placeholder: String
    let imageResourceName: String
    var storage: String = "email"
}

I would like to set text binding from storage var of this struct, is that possible by referencing a label?

ForEach(inputFields, id: \.self) { inputStruct in
    TextField(inputStruct.placeholder, text: \.$storage)
}

(on the top of the view I have)

@State private var email = "") ?

Upvotes: 2

Views: 636

Answers (1)

Asperi
Asperi

Reputation: 258443

Here is possible variant

ForEach(Array(inputFields.enumerated()), id: \.1) { index, inputStruct in
    TextField(inputStruct.placeholder, text: self.$inputFields[index].storage)
}

Upvotes: 3

Related Questions