1

I want to use List(data:, editActions:, rowContent:), the data: needs a $property, but I can't pass $persons in there directly. Is there any way to solve like this below:

import SwiftUI
import SwiftData

struct BindableTest: View {
    @Environment(\.modelContext) var modelContext
    @Query var persons: [Person]
    
    var body: some View {
        VStack {
            Button("Add") {
                let person = Person(name: "test", age: 12)
                modelContext.insert(person)
            }
            
            List($persons, editActions: .all) { $person in
                Text(person.name)
                
                Text(person.age.formatted())
            }
        }
    }
}

I saw this question is similar to my question: https://stackoverflow.com/questions/76464884/swiftdata-list-bindings-with-query, but those answers don't suit my situation.

2
  • Binding to a Query is impossible, it is read only and Binding is for value types. Person is a reference. Commented Feb 8, 2024 at 17:30
  • Here's the solution (since the question is closed I can't answer properly): Remove the editActions: .all argument. Add a .onMove and .onDelete closure, which will (re)enable list editing. Add @Bindable var person inside the list closure, e.g. ``` List(persons) { person in @Bindable var person = person } .onDelete { indexSet in } .onMove { indexSet, arg in } ``` Commented May 2, 2024 at 21:55

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.