了解 SwiftData 和绑定/更新,一个基本示例

Understanding SwiftData and bindings/updates, a bare bones example

提问人:Nerdy Bunz 提问时间:11/17/2023 更新时间:11/17/2023 访问量:53

问:

在编写这段代码时,我试图通过制作一个基本示例来验证我对 SwiftData 的了解。

这工作原理:

import SwiftUI

@main
struct WWPDApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                
        }
        // this makes modelContext available in the app
        .modelContainer(for: Memo.self)
    }
}

struct ContentView: View {
    // for getting swiftdata
    @Query private var memos: [Memo]
    // for setting swiftdata
    @Environment(\.modelContext) var modelContext
    
    var body: some View {
        
        VStack {
            Button("ADD MEMO") {
                modelContext.insert(Memo(name: "new memo"))
            }
            List(memos) {memo in
                Text(memo.name)
            }
        }
        .padding()
    }
}

// Putting "@Model" here makes this class work with swift data
@Model
final class Memo {
    
    var id: UUID
    var name: String
    
    init(id: UUID = UUID(), name: String) {
        self.id = id
        self.name = name
    }
    
}

这有效并验证了我们可以添加新对象并保存它们。

但是,我想验证并理解编辑/绑定方面。

我知道modelContext仅用于插入新对象。为了编辑现有对象,我们将依赖于与查询数组中包含的对象的双向绑定(?)...

所以我试了一下:

struct ContentView: View {
    // for getting swiftdata
    @Query private var memos: [Memo]
    // for setting swiftdata
    @Environment(\.modelContext) var modelContext
    
    var body: some View {
        
        // need to put some kind of @Bindable thingy here
        
        VStack {
            Button("ADD MEMO") {
                modelContext.insert(Memo(name: "new memo"))
            }
            List(memos) {memo in
                TextField("this doesn't work", text: memo.$name)
            }
        }
        .padding()
    }
}
iOS SwiftUI swift-data

评论


答:

1赞 workingdog support Ukraine 11/17/2023 #1

通过向协议添加一致性来启用类的更改跟踪。因此,当您需要绑定时,例如,您可以使用示例代码中所示的绑定。@Model final class Memo ...Observablememo.name@Bindable

struct ContentView: View {
    // for getting swiftdata
    @Query private var memos: [Memo]
    // for setting swiftdata
    @Environment(\.modelContext) var modelContext
    
    var body: some View {
        VStack {
            Button("ADD MEMO") {
                modelContext.insert(Memo(name: "new memo"))
            }
            List(memos) { memo in
                @Bindable var memo = memo  // <--- here
                TextField("this works", text: $memo.name)  // <--- here
            }
        }
        .padding()
    }
}

评论

0赞 Nerdy Bunz 11/17/2023
谢谢!这太奇怪了,我发誓我试过了......但我一定做错了什么。