Reputation: 247
import SwiftUI
import Combine
struct ContentView: View {
var subtract = MinusToObject()
var body: some View {
VStack{
Text("The number is \(MyObservedObject.shared.theObservedObjectToPass)")
Text("Minus")
.onTapGesture {
subtract.subtractIt()
}
NavigationView {
NavigationLink(destination: AnotherView()) {
Text("Push")
}.navigationBarTitle(Text("Master"))
}
}
}
}
class MyObservedObject: ObservableObject {
static let shared = MyObservedObject()
private init() { }
@Published var theObservedObjectToPass = 6
}
struct MinusToObject {
func subtractIt() {
MyObservedObject.shared.theObservedObjectToPass -= 1
}
}
When I hit the Minus
to call the function of my subtract
instance, I know the value changes because if I go to another View I can see the new value, but the current view doesn't update.
I think I have to put a property wrapper around var subtract = MinusToObject()
(I've tried several pretty blindly) and I feel like I should put a $
somewhere for a two-way binding, but I can't figure out quite where.
Upvotes: 1
Views: 99
Reputation: 257493
The MinusToObject
is redundant. Here is way (keeping MyObservedObject shared if you want)...
struct ContentView: View {
@ObservedObject private var vm = MyObservedObject.shared
//@StateObject private var vm = MyObservedObject.shared // << SwiftUI 2.0
var body: some View {
VStack{
Text("The number is \(vm.theObservedObjectToPass)")
Text("Minus")
.onTapGesture {
self.vm.theObservedObjectToPass -= 1
}
NavigationView {
NavigationLink(destination: AnotherView()) {
Text("Push")
}.navigationBarTitle(Text("Master"))
}
}
}
}
Upvotes: 1