Swift : Why is my View Model with a binding not working with the Toggle in my View? - swift

I have a view with a separate view model for it's logic. In my view model I've created a binding and I want the Toggle in my View to reflect and act on this. But it the moment, the view reads the initial state of my binding, but it does not allow me to update it (I can't move the toggle box). And I have no idea why this is.
This is my View (simplified):
public var viewModel: MyViewModel // passed as a dependency to my view
var body: some View {
Toggle("Test", isOn: viewModel.isOn)
}
This is the code in my ViewModel:
public var isOn: Binding<Bool> = .constant(false) {
didSet {
print("Binding in practice!")
}
}
As I said, the code runs, and the initial value for isOn is respected: if I set it to .constant(true) or .constant(false) the checkbox is in the correct state. But I am not allowed to change the checkbox. Also the print()-statement is never executed. So it seems to me there are 2 problems:
I cannot change the state for isOn
The didSet is not executed
Can anyone point me in the right direction?
Edit:
So, actually some of you pointed my in the direction I've already tried and that did not work. In the above writing I simplified my use case, but it's actually a bit more abstract than that: I've got a protocol for my View Model that I use as a dependency. What I've got working now (with binding and observing) is the following:
ViewModelProtocol + ViewModel:
public protocol ViewModelProtocol: ObservableObject {
var isOn: Binding<Bool> { get }
}
public class ViewModel: ViewModelProtocol {
private var _isOn: Bool = false
public var isOn: Binding<Bool> {
Binding<Bool>(
get: { self._isOn },
set: {
self._isOn = $0
// custom code
}
)
}
// More code that has #Published properties
}
View:
struct MyView<Model>: View where Model: ViewModelProtocol {
#ObservedObject var viewModel: Model
var body: some View {
Toggle("Test", isOn: viewModel.isOn)
// More code that uses #Published properties
}
}
Once again, I simplified the example and stripped out all clutter, but with this setup I am able to do what I want. However, I'm still not sure if this is the correct way to do this.
The implementation of making my view generic is based on https://stackoverflow.com/a/59504489/1471590

If you want to drive your view from the properties of the view model, then make it an ObservableObject
class ViewModel: ObservableObject {
#Published var isOn = false {
didSet {
print("Binding in practice")
}
}
}
And in your view, you can bind the toggle to this value:
struct ContentView: View {
#StateObject private var viewModel = ViewModel()
var body: some View {
Toggle("Test", isOn: $viewModel.isOn)
}
}

After some more tinkering and the response of #RajaKishan I came up with the following solution that works:
private var _isOn: Bool = false
public var isOn: Binding<Bool> {
Binding<Bool>(
get: { self._isOn },
set: {
self._isOn = $0
print("Room for custom logic")
}
)
}

Related

swiftui text view does not update when the property of class changes

A ton of similar questions found, but they all have different conditions - none of them seems to apply to my case.
The Text() view does not update with the property of the class, but the bush button prints the correct value. More info in the snippets.
The View:
import SwiftUI
struct ContentView: View {
#State private var client : Client = Client()
var body: some View {
VStack{
Text(client.message) // This view remains constant
...
Button( action: {
print("\(client.message)") // Prints correct updated value
}){
Text("Mess")
}
}
}
}
The Class:
class Client : ObservableObject{
private var mqtt: CocoaMQTT!
#Published var message : String = "Empty"
...
func get_message(mess : String){
self.message = mess
self.objectWillChange.send()
}
}
Even objectWillChange.send() does not seem to trigger the change in the view. Any ideas?
For Objects use #StateObject property wrapper and for String, Int, etc use #State property wrapper.
#State: We use this property wrapper when we observe a property that is exists inside our ContentView.
#StateObject: We use this property wrapper when we are observing properties that exists outside of our ContentView like in our Object, we can observe that property changes by firstly conforming that class to ObservableObject Protocol and marking that property as #Published inside our Object.
struct ContentView: View {
#StateObject private var client : Client = Client()
var body: some View {
VStack{
Text(client.message)
Button( action: {
print("\(client.message)")
}){
Text("Mess")
}
}
}
}
class Client : ObservableObject{
private var mqtt: CocoaMQTT!
#Published var message : String = "Empty"
func get_message(mess : String){
self.message = mess
}
}

SwiftUI not update view using #Published

I can't update the color of my Text base on the current status of my object.
The text should change color base on the variable status true or false.
I try below to simplify the code of where the data come from.
My contentview:
struct ContentView: View {
#StateObject var gm = GameManager()
#State var openSetting = false
var body: some View {
Button {
openSetting.toggle()
} label: {
Text("Setting")
}
}
}
ContentView has a SettingView where I'm selecting setting and where I want to update my textColor based on the status of object
struct SettingView: View {
#StateObject var gm : GameManager
var body: some View {
ScrollView(.horizontal, showsIndicators: true) {
HStack(spacing: 20) {
ForEach(gm.cockpit.ecamManager.door.doorarray) { doorName in
Button {
gm.close(door: doorName.doorName)
} label: {
Text(doorName.doorName)
// Here where I want to change color
.foregroundColor(doorName.isopen ? .orange : .green)
}
}
}
}
}
}
The data come from GameManager which inside has a variable called cockpit:
class GameManager: NSObject, ObservableObject, ARSessionDelegate, ARSCNViewDelegate {
#Published var cockpit = MakeCockpit() // create the cockpit
// do other stuff
}
MakeCockpit :
class MakeCockpit: SCNNode, ObservableObject {
#Published var ecamManager = ECAMManager()
// do other stuff
ECAMManager:
class ECAMManager: ObservableObject {
#Published var door = ECAMDoor()
#Published var stanby = ECAMsby()
}
And Finally... the Array I want to watch is in ECAMDoor class:
class ECAMDoor: ObservableObject {
#Published var doorarray : [Door] = [] // MODEL
}
Now everything work fine as expected but the #Publish of the door array not update my color in the setting view. I need to close the view and open again to se the color update.
Is someone can tell me where I mistake? I probably missed something .. hope I been clear (to many instance of class inside other class)

Changing #Published value triggers Init in View

I am facing a problem initializing the view, it is reinitialized when the #Published property is set and I cannot figure out why.
The app structure is:
MyApp -> MainView -> fullscreenCover OrderView -> ListOfOrders -> fullscreenCover ProductView -> Bug Button. The view model is injected as #StateObject.
Here is a simplified version of the app I'm working on:
View model
class SystemService: ObservableObject {
#Published private(set) var testValue: Bool = false
#Published private(set) var products: [Product] = []
}
The App declaration
#main
struct MyApp: App {
#StateObject private var systemService = SystemService()
#ViewBuilder
var body: some Scene {
WindowGroup {
MainView(systemService: systemService)
}
}
}
The main view, which basically just shows a fullscreen modal view - OrderView
struct MainView: View {
#StateObject var systemService: SystemService
#State private var activeFullScreen: ActiveFullScreenEnum?
var body: some View {
VStack {
Button(action: {
activeFullScreen = .order
}, label: Text("Order Details"))
}
.fullScreenCover(item: $activeFullScreen, content: { item in
switch item {
case .order:
OrderView(systemService: systemService)
}
})
}
}
The Order View contains a list of products.
struct OrderView: View {
#StateObject var systemService: SystemService
#State private var activeFullScreen: OrderFullScreenEnum?
init(systemService: SystemService) {
_systemService = StateObject(wrappedValue: systemService)
print("OrderScreen Initialized")
}
var body: some View {
VStack {
ScrollView {
ForEach(systemService.products) { product in
Button(action: {
activeFullScreen = .product(product)
}, label: Text("Prodcut Details"))
}
}
}
.fullScreenCover(item: $activeFullScreen, content: { item in
switch item {
case .product(let product):
ProductView(systemService: systemService, product: product)
}
})
}
}
And finally the Product View where the bug is discovered.
The bug is - when pressing on the "Bug Button" the ProductView is dismisses, and OrderView's init calls and prints out "OrderScreen Initialized".
struct ProductView: View {
#StateObject var systemService: SystemService
var body: some View {
VStack {
Button(action: {
systemService.testValue.toggle()
}, label: Text("Bug Button"))
}
}
}
Probably the issue in my fundamental misunderstanding of how Combine works, I will be grateful if somebody could help.
***** Additional info *****
If I add .onAppear to the Order View
.onAppear {
print("Order View Did Appear")
}
The first call to systemService.testValue.toggle() from the Ordre View triggers .onAppear, but only once, only the first time. After that, the bug disappears and .fullScreenCover doesn't get dismissed anymore.
I think the main problem is that the application may be trying to operate with four different instances of SystemServices.
#StateObject - 'A property wrapper type that instantiates an observable object.'
#ObservedObject - 'A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.'
Instead of #StateObject, try giving #ObservedObject in the child views of App a go.
Good luck.

SwiftUI: ObservableObject does not persist its State over being redrawn

Problem
In Order to achieve a clean look and feel of the App's code, I create ViewModels for every View that contains logic.
A normal ViewModel looks a bit like this:
class SomeViewModel: ObservableObject {
#Published var state = 1
// Logic and calls of Business Logic goes here
}
and is used like so:
struct SomeView: View {
#ObservedObject var viewModel = SomeViewModel()
var body: some View {
// Code to read and write the State goes here
}
}
This workes fine when the Views Parent is not being updated. If the parent's state changes, this View gets redrawn (pretty normal in a declarative Framework). But also the ViewModel gets recreated and does not hold the State afterward. This is unusual when you compare to other Frameworks (eg: Flutter).
In my opinion, the ViewModel should stay, or the State should persist.
If I replace the ViewModel with a #State Property and use the int (in this example) directly it stays persisted and does not get recreated:
struct SomeView: View {
#State var state = 1
var body: some View {
// Code to read and write the State goes here
}
}
This does obviously not work for more complex States. And if I set a class for #State (like the ViewModel) more and more Things are not working as expected.
Question
Is there a way of not recreating the ViewModel every time?
Is there a way of replicating the #State Propertywrapper for #ObservedObject?
Why is #State keeping the State over the redraw?
I know that usually, it is bad practice to create a ViewModel in an inner View but this behavior can be replicated by using a NavigationLink or Sheet.
Sometimes it is then just not useful to keep the State in the ParentsViewModel and work with bindings when you think of a very complex TableView, where the Cells themself contain a lot of logic.
There is always a workaround for individual cases, but I think it would be way easier if the ViewModel would not be recreated.
Duplicate Question
I know there are a lot of questions out there talking about this issue, all talking about very specific use-cases. Here I want to talk about the general problem, without going too deep into custom solutions.
Edit (adding more detailed Example)
When having a State-changing ParentView, like a list coming from a Database, API, or cache (think about something simple). Via a NavigationLink you might reach a Detail-Page where you can modify the Data. By changing the data the reactive/declarative Pattern would tell us to also update the ListView, which would then "redraw" the NavigationLink, which would then lead to a recreation of the ViewModel.
I know I could store the ViewModel in the ParentView / ParentView's ViewModel, but this is the wrong way of doing it IMO. And since subscriptions are destroyed and/or recreated - there might be some side effects.
Finally, there is a Solution provided by Apple: #StateObject.
By replacing #ObservedObject with #StateObject everything mentioned in my initial post is working.
Unfortunately, this is only available in ios 14+.
This is my Code from Xcode 12 Beta (Published June 23, 2020)
struct ContentView: View {
#State var title = 0
var body: some View {
NavigationView {
VStack {
Button("Test") {
self.title = Int.random(in: 0...1000)
}
TestView1()
TestView2()
}
.navigationTitle("\(self.title)")
}
}
}
struct TestView1: View {
#ObservedObject var model = ViewModel()
var body: some View {
VStack {
Button("Test1: \(self.model.title)") {
self.model.title += 1
}
}
}
}
class ViewModel: ObservableObject {
#Published var title = 0
}
struct TestView2: View {
#StateObject var model = ViewModel()
var body: some View {
VStack {
Button("StateObject: \(self.model.title)") {
self.model.title += 1
}
}
}
}
As you can see, the StateObject Keeps it value upon the redraw of the Parent View, while the ObservedObject is being reset.
I agree with you, I think this is one of many major problems with SwiftUI. Here's what I find myself doing, as gross as it is.
struct MyView: View {
#State var viewModel = MyViewModel()
var body : some View {
MyViewImpl(viewModel: viewModel)
}
}
fileprivate MyViewImpl : View {
#ObservedObject var viewModel : MyViewModel
var body : some View {
...
}
}
You can either construct the view model in place or pass it in, and it gets you a view that will maintain your ObservableObject across reconstruction.
Is there a way of not recreating the ViewModel every time?
Yes, keep ViewModel instance outside of SomeView and inject via constructor
struct SomeView: View {
#ObservedObject var viewModel: SomeViewModel // << only declaration
Is there a way of replicating the #State Propertywrapper for #ObservedObject?
No needs. #ObservedObject is-a already DynamicProperty similarly to #State
Why is #State keeping the State over the redraw?
Because it keeps its storage, ie. wrapped value, outside of view. (so, see first above again)
You need to provide custom PassThroughSubject in your ObservableObject class. Look at this code:
//
// Created by Франчук Андрей on 08.05.2020.
// Copyright © 2020 Франчук Андрей. All rights reserved.
//
import SwiftUI
import Combine
struct TextChanger{
var textChanged = PassthroughSubject<String,Never>()
public func changeText(newValue: String){
textChanged.send(newValue)
}
}
class ComplexState: ObservableObject{
var objectWillChange = ObservableObjectPublisher()
let textChangeListener = TextChanger()
var text: String = ""
{
willSet{
objectWillChange.send()
self.textChangeListener.changeText(newValue: newValue)
}
}
}
struct CustomState: View {
#State private var text: String = ""
let textChangeListener: TextChanger
init(textChangeListener: TextChanger){
self.textChangeListener = textChangeListener
print("did init")
}
var body: some View {
Text(text)
.onReceive(textChangeListener.textChanged){newValue in
self.text = newValue
}
}
}
struct CustomStateContainer: View {
//#ObservedObject var state = ComplexState()
var state = ComplexState()
var body: some View {
VStack{
HStack{
Text("custom state View: ")
CustomState(textChangeListener: state.textChangeListener)
}
HStack{
Text("ordinary Text View: ")
Text(state.text)
}
HStack{
Text("text input: ")
TextInput().environmentObject(state)
}
}
}
}
struct TextInput: View {
#EnvironmentObject var state: ComplexState
var body: some View {
TextField("input", text: $state.text)
}
}
struct CustomState_Previews: PreviewProvider {
static var previews: some View {
return CustomStateContainer()
}
}
First, I using TextChanger to pass new value of .text to .onReceive(...) in CustomState View. Note, that onReceive in this case gets PassthroughSubject, not the ObservableObjectPublisher. In last case you will have only Publisher.Output in perform: closure, not the NewValue. state.text in that case would have old value.
Second, look at the ComplexState class. I made an objectWillChange property to make text changes send notification to subscribers manually. Its almost the same like #Published wrapper do. But, when the text changing it will send both, and objectWillChange.send() and textChanged.send(newValue). This makes you be able to choose in exact View, how to react on state changing. If you want ordinary behavior, just put the state into #ObservedObject wrapper in CustomStateContainer View. Then, you will have all the views recreated and this section will get updated values too:
HStack{
Text("ordinary Text View: ")
Text(state.text)
}
If you don't want all of them to be recreated, just remove #ObservedObject. Ordinary text View will stop updating, but CustomState will. With no recreating.
update:
If you want more control, you can decide while changing the value, who do you want to inform about that change.
Check more complex code:
//
//
// Created by Франчук Андрей on 08.05.2020.
// Copyright © 2020 Франчук Андрей. All rights reserved.
//
import SwiftUI
import Combine
struct TextChanger{
// var objectWillChange: ObservableObjectPublisher
// #Published
var textChanged = PassthroughSubject<String,Never>()
public func changeText(newValue: String){
textChanged.send(newValue)
}
}
class ComplexState: ObservableObject{
var onlyPassthroughSend = false
var objectWillChange = ObservableObjectPublisher()
let textChangeListener = TextChanger()
var text: String = ""
{
willSet{
if !onlyPassthroughSend{
objectWillChange.send()
}
self.textChangeListener.changeText(newValue: newValue)
}
}
}
struct CustomState: View {
#State private var text: String = ""
let textChangeListener: TextChanger
init(textChangeListener: TextChanger){
self.textChangeListener = textChangeListener
print("did init")
}
var body: some View {
Text(text)
.onReceive(textChangeListener.textChanged){newValue in
self.text = newValue
}
}
}
struct CustomStateContainer: View {
//var state = ComplexState()
#ObservedObject var state = ComplexState()
var body: some View {
VStack{
HStack{
Text("custom state View: ")
CustomState(textChangeListener: state.textChangeListener)
}
HStack{
Text("ordinary Text View: ")
Text(state.text)
}
HStack{
Text("text input with full state update: ")
TextInput().environmentObject(state)
}
HStack{
Text("text input with no full state update: ")
TextInputNoUpdate().environmentObject(state)
}
}
}
}
struct TextInputNoUpdate: View {
#EnvironmentObject var state: ComplexState
var body: some View {
TextField("input", text: Binding( get: {self.state.text},
set: {newValue in
self.state.onlyPassthroughSend.toggle()
self.state.text = newValue
self.state.onlyPassthroughSend.toggle()
}
))
}
}
struct TextInput: View {
#State private var text: String = ""
#EnvironmentObject var state: ComplexState
var body: some View {
TextField("input", text: Binding(
get: {self.text},
set: {newValue in
self.state.text = newValue
// self.text = newValue
}
))
.onAppear(){
self.text = self.state.text
}.onReceive(state.textChangeListener.textChanged){newValue in
self.text = newValue
}
}
}
struct CustomState_Previews: PreviewProvider {
static var previews: some View {
return CustomStateContainer()
}
}
I made a manual Binding to stop broadcasting objectWillChange. But you still need to gets new value in all the places you changing this value to stay synchronized. Thats why I modified TextInput too.
Is that what you needed?
My solution is use EnvironmentObject and don't use ObservedObject at view it's viewModel will be reset, you pass through hierarchy by
.environmentObject(viewModel)
Just init viewModel somewhere it will not be reset(example root view).

Binding value from an ObservableObject

Aim:
I have a model which is an ObservableObject. It has a Bool property, I would like to use this Bool property to initialise a #Binding variable.
Questions:
How to convert an #ObservableObject to a #Binding ?
Is creating a #State the only way to initialise a #Binding ?
Note:
I do understand I can make use of #ObservedObject / #EnvironmentObject, and I see it's usefulness, but I am not sure a simple button needs to have access to the entire model.
Or is my understanding incorrect ?
Code:
import SwiftUI
import Combine
import SwiftUI
import PlaygroundSupport
class Car : ObservableObject {
#Published var isReadyForSale = true
}
struct SaleButton : View {
#Binding var isOn : Bool
var body: some View {
Button(action: {
self.isOn.toggle()
}) {
Text(isOn ? "On" : "Off")
}
}
}
let car = Car()
//How to convert an ObservableObject to a Binding
//Is creating an ObservedObject or EnvironmentObject the only way to handle a Observable Object ?
let button = SaleButton(isOn: car.isReadyForSale) //Throws a compilation error and rightly so, but how to pass it as a Binding variable ?
PlaygroundPage.current.setLiveView(button)
Binding variables can be created in the following ways:
#State variable's projected value provides a Binding<Value>
#ObservedObject variable's projected value provides a wrapper from which you can get the Binding<Subject> for all of it's properties
Point 2 applies to #EnvironmentObject as well.
You can create a Binding variable by passing closures for getter and setter as shown below:
let button = SaleButton(isOn: .init(get: { car.isReadyForSale },
set: { car.isReadyForSale = $0} ))
Note:
As #nayem has pointed out you need #State / #ObservedObject / #EnvironmentObject / #StateObject (added in SwiftUI 2.0) in the view for SwiftUI to detect changes automatically.
Projected values can be accessed conveniently by using $ prefix.
You have several options to observe the ObservableObject. If you want to be in sync with the state of the object, it's inevitable to observe the state of the stateful object. From the options, the most commons are:
#State
#ObservedObject
#EnvironmentObject
It is upto you, which one suits your use case.
No. But you need to have an object which can be observed of any change made to that object in any point in time.
In reality, you will have something like this:
class Car: ObservableObject {
#Published var isReadyForSale = true
}
struct ContentView: View {
// It's upto you whether you want to have other type
// such as #State or #ObservedObject
#EnvironmentObject var car: Car
var body: some View {
SaleButton(isOn: $car.isReadyForSale)
}
}
struct SaleButton: View {
#Binding var isOn: Bool
var body: some View {
Button(action: {
self.isOn.toggle()
}) {
Text(isOn ? "Off" : "On")
}
}
}
If you are ready for the #EnvironmentObject you will initialize your view with:
let contentView = ContentView().environmentObject(Car())
struct ContentView: View {
#EnvironmentObject var car: Car
var body: some View {
SaleButton(isOn: self.$car.isReadyForSale)
}
}
class Car: ObservableObject {
#Published var isReadyForSale = true
}
struct SaleButton: View {
#Binding var isOn: Bool
var body: some View {
Button(action: {
self.isOn.toggle()
}) {
Text(isOn ? "On" : "Off")
}
}
}
Ensure you have the following in your SceneDelegate:
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
.environmentObject(Car())
In my case i used .constant(viewModel) to pass viewModel to ListView #Binding var viewModel
Example
struct CoursesView: View {
#StateObject var viewModel = CoursesViewModel()
var body: some View {
ZStack {
ListView(viewModel: .constant(viewModel))
ProgressView().opacity(viewModel.isShowing)
}
}
}
struct ListView: View {
#Binding var viewModel: CoursesViewModel
var body: some View {
List {
ForEach(viewModel.courses, id: \.id) { course in
Text(couse.imageUrl)
}
}
}
}