-1

Currently I declare my ProgressView in my main view controller which gets it's value from a @State variable. On a button press i change the value of the variable which then updates the value of my progress bar.

I want to make changes to this ProgressView, but using a button on a separate view controller. I've tried to use Binding, but due to the way I am using WatchTabView, this forces me to declare a @Binding variable within my App struct, which isn't possible.

Not sure if I'm overthinking this, but how can i update my progress bar from another view?

Main View

struct ViewController: View {

@State var progressBarValue = 5.0 

 var body: some View {
        ScrollView{

  ProgressView("Effort", value: progressBarValue, total: 20)
        VStack {

 Button{ 

progressBarValue += 5.0

}label:{
Text("Click")
}

Other View

struct OtherViewController: View{

...

Button{

//I want to increase progressBarValue by clicking here

}label:{
Text("Click")
}

...
}
Gaz
  • 101
  • 1
  • 13

1 Answers1

0

First please read this post: What's the difference between a View and a ViewController?

Then read this: https://developer.apple.com/documentation/combine/observableobject

Also, read this: https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject

Finally, come back to this example:

class MyViewController: ObservableObject {
  @Published private(set) progress: Float = 0

  func updateProgress(by value: Float) {
    progress += value
  }
}

Parent View:

struct ParentView: View {
  @ObservedObject var myController = MyViewController()

  var body: some View {
    MainChildView()
      .environmentObject(myController) //this is one of the ways of passing down an ObservableObject to all underlying views.

    //your progress view code can go here
  }
}

MainChildView

struct MainChildView: View {
  //no need to pass anything into this view because of the EnvironmentObject.
  var body: some View {
    ChildView()
  }
}

ChildView

struct ChildView: View {
  @EnvironmentObject var myController: MyViewController //EnvironmentObject will search for MyViewController declared somewhere in one of the parent views

  var body: some View {
    //your progress view code can go here
    Button("Tap", action: {
      myController.updateProgress(by: 5)
    })
  }
}
someone
  • 46
  • 3