Home > Software design >  SwiftUI TextField Binding to a simple Model (non-class sturct)
SwiftUI TextField Binding to a simple Model (non-class sturct)

Time:11-01

I have a simple struct, that is decodable / codable and hashable.

public struct Field: Codable, Hashable {
    let key: String
    enum CodingKeys: String, CodingKey {
        case key
    }
}

In my SwiftUI, I'm creating an array, where I want to add and remove and Bind to the Struct values. But I am getting errors, that Struct is not Binding.

let decodableJSON = """
{
    "key": ""
}
"""
let settableInit: Field = try! JSONDecoder().decode(Field.self, from: decodableJSON.data(using: .utf8)!)

struct Test_view: View {
    
    @State
    var settableFields: [Field] = [settableInit]
    
    var body: some View {
        ForEach(settableFields, id: \.key) { (settableField: Field) in 
             TextField("Key", text: settableField.key)
        }

But I get an error, that settableField is not Binding. I have tried adding the settableInit as an @ObservableObject to the main Swift View, but it still doesn't work.

Is there a way, to have the View bind to Struct properties, and have TextField change these properties? It feels like something so trivial, but for some reason undoable for me.

Thank you for any pointers!

CodePudding user response:

In Xcode13 you can use the new element binding syntax:

public struct Field: Codable, Hashable {
    var key: String
    enum CodingKeys: String, CodingKey {
        case key
    }
}

struct Demo: View {
    
    @State var settableFields: [Field] = [Field(key: "1"), Field(key: "2")]
    
    var body: some View {
        ForEach($settableFields, id: \.key) { $settableField in
            TextField("Key", text: $settableField.key)
        }
    }
}

In earlier versions of Xcode you could use the indices of the array:

struct Demo: View {
    
    @State var settableFields: [Field] = [Field(key: "1"), Field(key: "2")]
    
    var body: some View {
        ForEach(settableFields.indices, id: \.self) { index in
            TextField("Key", text: $settableFields[index].key)
        }
    }
}
  • Related