1

I have a model called Hobby. I want to create a view that interates over all of the hobbies and displays each in a box in a scrolling HStack.

My code looks like this:

struct HobbiesHStack: View {

@Environment(\.modelContext) var context

@Query(sort: \Hobby.createdDate) private var hobbies: [Hobby]
    
var body: some View {
    HStack(spacing: 15) {
        ForEach(hobbies, id: \.self) { hobby in
            HobbyBox(hobby: hobby)
        }
    }
}    

}

This works fine. Except that now I want to add some functionality in that scrolling HStack which allows me to edit or add items to the Hobby model. So I think I want to create a binding on hobby that allows for the values to be in sync accross many different view. As I iterate throught the hobbies, I want to pass a binding of hobby to the HobbyBox subview.

Is this possible? Or even a good way to do it?

1
  • No, you can’t write to a Query (Binding is a two-way connection), just edit the item using Bindable and then save it, the query will update. Commented Nov 6, 2023 at 19:36

1 Answer 1

0

try this approach to "...add some functionality in that scrolling HStack which allows me to edit or add items to the Hobby model."

The example code shows how to edit the chosen Hobby

struct HobbiesHStack: View {
    @Environment(\.modelContext) var context
    @Query(sort: \Hobby.createdDate) private var hobbies: [Hobby]
    
    var body: some View {
        Spacer()
        ScrollView(.horizontal) {  // <-- here Scrolling
            HStack(spacing: 10) {
                ForEach(hobbies, id: \.self) { hobby in
                    HobbyBox(hobby: hobby).border(.red)
                }
            }
        }
        Spacer()
    }
}

struct HobbyBox: View {
    @Bindable var hobby: Hobby  // <-- here
    
    var body: some View {
        TextField("hobby", text: $hobby.name) // <-- here edit the data
            .padding(10)
    }
}

struct ContentView: View {
    @Environment(\.modelContext) private var context
    
    var body: some View {
        HobbiesHStack()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.