Vasco
Vasco

Reputation: 47

Swift detect changes to a variable from another view within a view

I have the following Class

class GettingData: ObservableObject {

var doneGettingData = false
    
        {
        didSet {
            if doneGettingData {
                print("The instance property doneGettingData is now true.")
            } else {
                print("The instance property doneGettingData is now false.")
            }

        }
    }
}

And I'm updating the variable doneGettingData within a mapView structure that then I'm using in my main view (contentView). This variable its changing from false / true while the map gets loaded and I can detecte it from the print that I have used in the class so I know it's changing. I want to use it to trigger a spinner within ContentView where I have the following code:

import SwiftUI
import Combine

struct ContentView: View {
   
var done = GettingData().doneGettingData

 var body: some View {
        
        VStack {
            MapView().edgesIgnoringSafeArea(.top)
            Spacer()
            Spinner(isAnimating: done, style: .large, color: .red)
            
    }
}



struct Spinner: UIViewRepresentable {
    let isAnimating: Bool
    let style: UIActivityIndicatorView.Style
    let color: UIColor
    
    func makeUIView(context: UIViewRepresentableContext<Spinner>) -> UIActivityIndicatorView {
        let spinner = UIActivityIndicatorView(style: style)
        spinner.hidesWhenStopped = true
        spinner.color = color
        return spinner
    }
    
    func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<Spinner>) {
        isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

What should I do in order to the variable to change as it is changing with the print but inside the view ? I have tried many options but nothing works ! Thank you

Upvotes: 1

Views: 1344

Answers (1)

Asperi
Asperi

Reputation: 258365

Make your property published

class GettingData: ObservableObject {
  @Published var doneGettingData = false
}

then make data observed and pass that instance into MapView for use, so modify that property internally

struct ContentView: View {
   
   @ObservedObject var model = GettingData()

   var body: some View {
        VStack {
            MapView(dataGetter: model).edgesIgnoringSafeArea(.top)
            Spacer()
            Spinner(isAnimating: model.doneGettingData, style: .large, color: .red)
            
    }
}

Upvotes: 1

Related Questions