简体   繁体   English

SwiftUI TextField 绑定到一个简单的模型(非类结构)

[英]SwiftUI TextField Binding to a simple Model (non-class sturct)

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.在我的 SwiftUI 中,我正在创建一个数组,我想在其中添加和删除以及绑定到 Struct 值。 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.但是我收到一个错误, settableField不是 Binding。 I have tried adding the settableInit as an @ObservableObject to the main Swift View, but it still doesn't work.我尝试将settableInit作为 @ObservableObject 添加到主 Swift 视图,但它仍然不起作用。

Is there a way, to have the View bind to Struct properties, and have TextField change these properties?有没有办法让 View 绑定到 Struct 属性,并让TextField更改这些属性? It feels like something so trivial, but for some reason undoable for me.这感觉就像是一件微不足道的事情,但由于某种原因对我来说是无法挽回的。

Thank you for any pointers!感谢您的任何指点!

In Xcode13 you can use the new element binding syntax:Xcode13 中,您可以使用新的元素绑定语法:

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:早期版本的 Xcode 中,您可以使用数组的索引:

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

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

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