0
votes

I have a swiftUi view that shows a map with annotations ( dots in a map ) and I have created a Boolean variable that changes from false to true when all the annotations are finished being displayed. Now in ContentView I have a Spinner that I would like to display while the variable is false and stop when its true. This variable its a global variable and with the following test I know it changes

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

The issue is that if for example in the ContentView if I use Text("Did it change = \(doneGettingData.description)") just for testing proposes - Its false all the time although I do see it changing with the print !! enter image description here

How should I solve this ? I'm missing something, Any suggestions please ? Thank you

1

1 Answers

0
votes

It is not seen all code and places of usage, but it looks most appropriate to wrap that global variable into ObservableObject class and use object of this class (by reference of course) in all needed places, as well as have it observed in SwiftUI view to automatic refresh, ie

class GettingData: ObservableObject {
    let shared = GettingData()         // << to use in MapKit & in SwiftUI

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

struct DemoView: View {
    @ObservedObject var vm = GettingData.shared

    var body: some View {
        VStack {
            Text("Did it change = \(vm.doneGettingData.description)")
        }
    }
}