So I have a super-simple model, and a super-simple GUI as follows:
class SomeModel: BindableObject {
var didChange = PassthroughSubject<Void, Never>()
var n1: Int = 0 {
didSet { didChange.send()
print("Did change was called on n1") }
}
}
struct ContentView : View {
@Binding var n1: Int
// imagine some GUI which displays n1, mutates it on a button click, etc.
}
So far so good. But what I want to do now is to pass a binding to the model's n1 property into the view. I do that as follows: in the spot in the boilerplate SceneDelegate.swift file you get, I wrote this:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
@ObjectBinding var theModel = SomeModel()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let rootView = ContentView(n1: $theModel.n1)
window.rootViewController = UIHostingController(rootView: rootView)
//etc.
}
}
}
Now when I click on my button, which is wired to mutate via the n1 variable in ContentView, the print statement fires, but the GUI never updates. No compiler warnings, etc. Why isn't SwiftUI tracking the dependency? I passed it in a binding...
Is this illegal? Do I have to instead always give the ContentView object an @BindableObject property that references the model, and then pull the value out of the model to use it? I'm basically trying to make global predicate/values that live in a model available to the UI without passing in an entire model.
(My use case for this is: imagine a global variable that indicates whether or not my app is in connection with my company's network. I use this all over the place, so it's useful to think of it just as a global bool variable "isCompanyNetworkReachable". So I'd like to pass just that single value around, use it as a bool in expressions, etc. and have the GUI be able to react to state changes on it. It would be annoying to always have to write:
`Text(isCompanyNetworkReachable.value ? "" : "Working offline")`
when I want to write
` Text(isCompanyNetworkReachable ? "" : "Working offline")`
so i'm trying to pass into the view a binding object, and NOT the enclosing model itself, if that makes sense.