GM, I'm kinda new in SwiftData, I'm trying to build an app with Steppers and I need to acess the value of steppers in other views and save them. I started with this code but it doen't save the results, can someone please help? Thanks alot.
import SwiftData
@main
struct TesteStepApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: GroceryListItem.self)
}
}
@Model
class GroceryListItem {
let stepperValue: Int
init(stepperValue: Int = 0) {
self.stepperValue = stepperValue
}
}
struct ContentView: View {
@Environment(\.modelContext) var context
@State private var stepperValue: Int = 0
var body: some View {
VStack {
Stepper("Value: \(stepperValue)", value: $stepperValue, in: 0...100)
.padding()
}
.padding()
.onChange(of: stepperValue) { oldValue, newValue in
insertValue(newValue)
}
}
private func insertValue(_ value: Int) {
}
}
#Preview {
ContentView()
}
The stepper should act on the model that is stored in memory.
Here you are inserting a new value, but it should increase the stepperValue
in an entity of GroceryListItem
.
First you need to create an entity, and save it.
let item = GroceryListItem()
context.insert(item)
Then you need to load that item, and use it in a binding to directly bind the stepper to its value.
This could become your list of elements:
List {
ForEach(items) { item in
@Bindable var bindingItem = item
NavigationLink {
// Destination view, a simple Stepper.
Stepper(value: $bindingItem.stepperValue) {
Text("\(item.stepperValue)")
}
} label: {
Text("Item with value: \(item.stepperValue)")
}
}
}
onChange
is not needed for this. :)