Hi all!
I am trying to understand why the Stepper's
title, where model.count.formatted()
is passed in, doesn't update when I tap the buttons on the Stepper
? (Yet the model.count
is updated on the struct Row: View
?)
I know this may not be the optimal code, but I'm trying to understand how @Binding
behaves in different scenarios.
Thanks!
import SwiftUI
// MARK: - Model
struct Model {
let title: String
var count: Int
}
extension Model: Identifiable {
var id: String {
title
}
}
// MARK: - StateProvider
final class StateProvider: ObservableObject {
@Published
var data: [Model] = [
Model(title: "Elephant", count: 3),
]
}
// MARK: - Detail View
struct DetailView: View {
@Binding
var model: Model
var body: some View {
ScrollView {
Text(model.title)
.font(.title)
Stepper(model.count.formatted()) {
model.count += 1
} onDecrement: {
model.count -= 1
}
.padding()
}
}
}
// MARK: - List View
struct Row: View {
@Binding
var model: Model
var body: some View {
HStack {
Text(model.title)
Spacer()
Text(model.count.formatted())
}
}
}
struct ContentView: View {
@StateObject
private var stateProvider = StateProvider()
var body: some View {
NavigationStack {
List {
ForEach($stateProvider.data) { model in
NavigationLink {
DetailView(model: model)
} label: {
Row(model: model)
}
}
}
}
}
}
// MARK: - Preview
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(.dark)
}
}