SwiftUI view not getting updated on changing #ObservedObject - ios

Here is a simple MVVM based TestView:
import SwiftUI
public struct Test: View {
#ObservedObject public var viewModel = TestViewModel()
public init() {
}
public var body: some View {
VStack {
Text(viewModel.model.stri)
Button(action: {
self.viewModel.change()
}) {
Text("Change")
}
}.padding(50)
}
}
public class TestModel {
#Published public var condition: Bool = false
#Published var stri = "Random numbers"
}
public class TestViewModel: ObservableObject {
#Published var model = TestModel()
func change() {
model.condition.toggle()
model.stri = "\(Int.random(in: 1...10))"
}
}
The view does not get updated when the model is updated from inside the view model.
The text should finally produce some random number between 1 and 10. Please let me know where I am going wrong.

It is because your Test view observes viewModel but not viewModel.model which is not changed in your scenario because it is a reference-type
The following is a solution
func change() {
model.condition.toggle()
model.stri = "\(Int.random(in: 1...10))"
self.objectWillChange.send() // << this one !!
}

Related

Working with SwiftUI views and StateObject in packages

I created a SwiftUI view and ObservableObject in a package like this one:
struct CustomView: View {
#StateObject
var viewModel: CustomViewModel
var body: some View {
Text("Test")
}
}
class CustomViewModel: ObservableObject {
var folderName: String
init(folderName: String) {
self.folderName = folderName
}
}
I'm using this like here:
struct ContentViewInsidePackage: View {
var body: some View {
CustomView(viewModel: CustomViewModel(folderName: "Winter"))
}
}
How can I use the View and ObservableObject outside of the package?
The problem is when I'm using this view outside of the package then I need to declare everything public and I need a public init like here:
public struct CustomView: View {
#StateObject
var viewModel: CustomViewModel
public init(viewModel: CustomViewModel) {
// Compile Error: Cannot assign to property: 'viewModel' is a get-only property
self.viewModel = viewModel
}
public var body: some View {
Text("Test")
}
}
public class CustomViewModel: ObservableObject {
var folderName: String
public init(folderName: String) {
self.folderName = folderName
}
}
Then I get the compile error: Cannot assign to property: 'viewModel' is a get-only property
How can I instantiate the ObservableObject with the values I want to inject?
Try this:
public struct CustomView: View {
#StateObject
var viewModel: CustomViewModel
public init(viewModel: CustomViewModel) {
// Note the change on the below line:
self._viewModel = StateObject(wrappedValue: viewModel)
}
public var body: some View {
Text("Test")
}
}
public class CustomViewModel: ObservableObject {
var folderName: String
public init(folderName: String) {
self.folderName = folderName
}
}

Using #StateObject in iOS 14.0 while supporting iOS 13.0

I need help finding the best way to support the new #StateObject in iOS 14.0 and still supporting some alternative in iOS 13.0. Admittedly, I do not know what is the best approach in iOS 13.0. Below is what I currently have.
Does anyone have ideas on a better approach?
struct HomeView: View {
let viewModel: HomeViewModel
var body: some View {
if #available(iOS 14, *) {
HomeViewWrapper(viewModel: viewModel)
} else {
CompatibleHomeViewWrapper(viewModel: viewModel)
}
}
}
#available(iOS 14, *)
private struct HomeViewWrapper: View {
#StateObject var viewModel: HomeViewModel
var body: some View {
CompatibleHomeView(viewModel: viewModel)
}
}
private struct CompatibleHomeViewWrapper: View {
#State var viewModel: HomeViewModel
var body: some View {
CompatibleHomeView(viewModel: viewModel)
}
}
struct CompatibleHomeView: View {
#ObservedObject var viewModel: HomeViewModel
var body: some View {
Text(viewModel.someRandomName)
}
}
You can get the #StateObject behaviour by wrapping a custom propertyWrapper around #State and #ObservedObject like so:
import Combine
import PublishedObject // https://github.com/Amzd/PublishedObject
/// A property wrapper type that instantiates an observable object.
#propertyWrapper
public struct StateObject<ObjectType: ObservableObject>
where ObjectType.ObjectWillChangePublisher == ObservableObjectPublisher {
/// Wrapper that helps with initialising without actually having an ObservableObject yet
private class ObservedObjectWrapper: ObservableObject {
#PublishedObject var wrappedObject: ObjectType? = nil
init() {}
}
private var thunk: () -> ObjectType
#ObservedObject private var observedObject = ObservedObjectWrapper()
#State private var state = ObservedObjectWrapper()
public var wrappedValue: ObjectType {
if state.wrappedObject == nil {
// There is no State yet so we need to initialise the object
state.wrappedObject = thunk()
}
if observedObject.wrappedObject == nil {
// Retrieve the object from State and observe it in ObservedObject
observedObject.wrappedObject = state.wrappedObject
}
return state.wrappedObject!
}
public init(wrappedValue thunk: #autoclosure #escaping () -> ObjectType) {
self.thunk = thunk
}
}
I use this myself too so I will keep it updated at:
https://gist.github.com/Amzd/8f0d4d94fcbb6c9548e7cf0c1493eaff
Note: The most upvoted comment was that ObservedObject was very similar, which is just not true at all.
StateObject retains the object between view inits AND relays object changes to the view through willChangeObserver.
ObservedObject only relays changes to the view BUT if you create it in the view init, every time the parent view changes the object will be initialised again (losing your state).
This explanation is very crude and there is better out there please read up on it as it is an impactful part of SwiftUI.
struct StateObjectView<ViewModel: ObservableObject, Content: View>: View {
let viewModel: ViewModel
let content: () -> Content
var body: some View {
VStack {
if #available(iOS 14, *) {
StateObjectView14(viewModel: viewModel, content: content)
} else {
StateObjectView13(viewModel: viewModel, content: content)
}
}
}
}
#available(iOS 14.0, *)
struct StateObjectView14<ViewModel: ObservableObject, Content: View>: View {
#SwiftUI.StateObject var viewModel : ViewModel
let content: () -> Content
var body: some View {
content()
.environmentObject(viewModel)
}
}
struct StateObjectView13<ViewModel: ObservableObject, Content: View>: View {
#Backport.StateObject var viewModel : ViewModel
let content: () -> Content
var body: some View {
content()
.environmentObject(viewModel)
}
}
Usage:
struct ContentView: View {
#State private var reset = false
var body: some View {
VStack {
Button("reset") {
reset.toggle()
}
ScoreView()
}
}
}
class ScoreViewModel: ObservableObject {
init() {
//score = 0
print("Model Created")
}
#Published var score: Int = 0
}
struct ScoreView: View {
let viewModel : ScoreViewModel = .init()
var body: some View {
StateObjectView(viewModel: viewModel) {
ScoreContentView()
}
.onAppear {
print("ScoreView Appear")
}
}
}
struct ScoreContentView: View {
//#ObservedObject var viewModel : ScoreViewModel = .init()
#EnvironmentObject var viewModel : ScoreViewModel
#State private var niceScore = false
var body: some View {
VStack {
Button("Add Score") {
viewModel.score += 1
print("viewModel.score: \(viewModel.score)")
if viewModel.score > 3 {
niceScore = true
}
}
Text("Content Score: \(viewModel.score)")
Text("Nice? \(niceScore ? "YES" : "NO")")
}
.padding()
.background(Color.red)
}
}
Backports:
https://github.com/shaps80/SwiftUIBackports

SwiftUI: calling a method from nested view

I am pretty nw to SwiftUI, and to make my code more readable, I usually break my views into smaller views.
Let's say I have a viewModel, what is the best way to call a method of my viewModel from a nested view? Right now I am passing around my ViewModel as a parameter of every nested view, but I don't find it very optimal and clean...
Is there a way to notify MyMainView that the button of HeaderSubview was tapped ? Can I use Combine for example?
ViewModel
class MyViewModel {
func fetchSomeData() {
print("Fetching Some Data")
}
}
MainView
struct MyMainView: View {
var myViewModel = MyViewModel()
var body: some View {
HeaderView(viewModel: myViewModel)
}
}
struct HeaderView: View {
var viewModel: MyViewModel
var body: some View {
HeaderSubview(viewModel: viewModel)
}
}
struct HeaderSubview: View {
var viewModel: MyViewModel
var body: some View {
Button("Search") {
// I want to call my View Model method here
viewModel.fetchSomeData()
}
}
}
You can make your class ObservableObject and inject it as environment object, so any subview can use it and main view would be able to observe it.
Something like
class MyViewModel: ObservableObject {
#Published var loading = false
func fetchSomeData() {
loading = true
DispatchQueue.global(qos: .background).async {
print("Fetching Some Data")
// ... long activity here
DispatchQueue.main.async { [weak self] in
self?.loading = false
}
}
}
}
struct MyMainView: View {
#StateObject var myViewModel = MyViewModel()
var body: some View {
HeaderView().environmentObject(myViewModel)
if myViewModel.loading {
Text("Loading...")
}
}
}
struct HeaderView: View {
var body: some View {
HeaderSubview()
}
}
struct HeaderSubview: View {
#EnvironmentObject var viewModel: MyViewModel
var body: some View {
Button("Search") {
// I want to call my View Model method here
viewModel.fetchSomeData()
}
}
}

How to run a method in ContentView when an ObservedObject changes in other class [Swift 5 iOS 13.4]

Here is my basic ContentView
struct ContentView: View
{
#ObservedObject var model = Model()
init(model: Model)
{
self.model = model
}
// How to observe model.networkInfo's value over here and run "runThis()" whenever the value changes?
func runThis()
{
// Function that I want to run
}
var body: some View
{
VStack
{
// Some widgets here
}
}
}
}
Here is my model
class Model: ObservableObject
{
#Published var networkInfo: String
{
didSet
{
// How to access ContentView and run "runThis" method from there?
}
}
}
I'm not sure if it is accessible ? Or if I can observe ObservableObject changes from View and run any methods?
Thanks in advance!
There are a number of ways to do this. If you want to runThis() when the
networkInfo changes then you could use something like this:
class Model: ObservableObject {
#Published var networkInfo: String = ""
}
struct ContentView: View {
#ObservedObject var model = Model()
var body: some View {
VStack {
Button(action: {
self.model.networkInfo = "test"
}) {
Text("change networkInfo")
}
}.onReceive(model.$networkInfo) { _ in self.runThis() }
}
func runThis() {
print("-------> runThis")
}
}
another global way is this:
class Model: ObservableObject {
#Published var networkInfo: String = "" {
didSet {
NotificationCenter.default.post(name: NSNotification.Name("runThis"), object: nil)
}
}
}
struct ContentView: View {
#ObservedObject var model = Model()
var body: some View {
VStack {
Button(action: {
self.model.networkInfo = "test"
}) {
Text("change networkInfo")
}
}.onReceive(
NotificationCenter.default.publisher(for: NSNotification.Name("runThis"))) { _ in
self.runThis()
}
}
func runThis() {
print("-------> runThis")
}
}

View refreshing not triggered when ObservableObject is inherited in SwiftUI

ContentView2 view is not refreshed when model.value changes, if Model conforms to ObservableObject directly instead of inheriting SuperModel then it works fine
class SuperModel: ObservableObject {
}
class Model: SuperModel {
#Published var value = ""
}
struct ContentView2: View {
#ObservedObject var model = Model()
var body: some View {
VStack {
Text(model.value)
Button("change value") {
self.model.value = "\(Int.random(in: 1...10))"
}
}
}
}
Here is working variant of your example. See that to be able to work, not only chaining the publishers is required, but at least one Published property. So or so, it could help in some scenario.
import SwiftUI
class SuperModel: ObservableObject {
// this is workaround but not real trouble.
// without any value in supermodel there is no real usage of SuperModel at all
#Published var superFlag = false
}
class Model: SuperModel {
#Published var value = ""
override init() {
super.init()
_ = self.objectWillChange.append(super.objectWillChange)
}
}
struct ContentView: View {
#ObservedObject var model = Model()
var body: some View {
VStack {
Text(model.value)
Button("change value") {
self.model.value = "\(Int.random(in: 1...10))"
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
changing the code to
var body: some View {
VStack {
Text(model.value)
Button("change value") {
self.model.value = "\(Int.random(in: 1...10))"
}
Text(model.superFlag.description)
Button("change super flag") {
self.model.superFlag.toggle()
}
}
}
you can see how to use even your supermodel at the same time
Use ObjectWillChange to solve the problem specified.
Here is the working code:
import SwiftUI
class SuperModel: ObservableObject {
}
class Model: SuperModel {
var value: String = "" {
willSet { self.objectWillChange.send() }
}
}
struct ContentView: View {
#ObservedObject var model = Model()
var body: some View {
VStack {
Text("Model Value1: \(model.value)")
Button("change value") {
self.model.value = "\(Int.random(in: 1...10))"
}
Text("Model Value2: \(model.value)")
}
}
}
This really looks like heavy defect.
class SuperModel: ObservableObject {
}
class Model: SuperModel {
#Published var value = ""
}
as I see the value is changed and keep new one as expected, but DynamicProperty feature does not work
The following variant works for me (Xcode 11.2 / iOS 13.2)
class SuperModel: ObservableObject {
#Published private var stub = "" // << required !!!
}
class Model: SuperModel {
#Published var value = "" {
willSet { self.objectWillChange.send() } // < works only if above
}
}
Also such case is possible for consideration:
class SuperModel {
}
class Model: SuperModel, ObservableObject {
#Published var value = ""
}

Resources