Home > Software design >  How to implement observer in swift
How to implement observer in swift

Time:06-02

I have the following project which implements an observer in swift in order to pass data between two Views.

Model

import Foundation

class ModelData : ObservableObject {
@Published var number: Int = 1
}

View1

import Foundation
import SwiftUI

struct SliderView: View {

@State private var text = "1"
@State private var isEditing = false
@State private var celsius: Double = 1

@StateObject var modelData = ModelData()

var body: some View {
    VStack {
        
        VStack {
            Text("Number from slider: \(Int(round(celsius)), specifier: "%d")")
            
            Slider(value: $celsius,
                   in: 1...20, step:1.0)
        }.onChange(of: celsius) { _ in
        
            self.text = String(Int(round(celsius)))
            self.modelData.number = Int(round(celsius))
        }
        
        HStack {
            Text("Number")
            Spacer()
            Text(String(text))
        }.padding()
    }
    }
    }

    struct SliderView_Previews: PreviewProvider {
    static var previews: some View {
    SliderView()
    }
    }

View2

import SwiftUI

struct SettingsView: View {
@ObservedObject var modelData = ModelData()

var body: some View {
    ZStack {
        Color.red
        VStack {
        Image("Settings")
            .foregroundColor(.blue)
            .font(.system(size: 100.0))
            Text(String(format: "Number is %d ", modelData.number))
        }
    }
    
}
}

The SettingsView is not updated when data is changed inside SliderView and it remains with the default value of ModelData.

Best regards, Aurelian

CodePudding user response:

In the View with your TabView, declare @StateObject var modelData = ModelData()

and pass it to View1 using .environmentObject(modelData).

In View1 use @EnvironmentObject var modelData: ModelData. Do the same for View2.

  • Related