1

I have the following viewfile:

import SwiftUI

class Progress: ObservableObject {
    @Published var index = 0
}

struct RegistrationView: View {
    @ObservedObject var progress: Progress
    var body: some View {
        TabView(selection: $progress.index) {
            setUsernameView(progress: self.progress).tabItem{}.tag(0)
            setMasterPasswordView().tabItem{}.tag(1)
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
    }
}

when I am finished with my setUserNameView() I want to update index to 1 so that it switches to setMasterPasswordView. Im passing progress to the view and then inside to another view which updates the value.

Now xcode complains: Missing argument for parameter 'progress' in call the call is in the contentView().

import SwiftUI

struct ContentView: View {
    var body: some View {
        RegistrationView()
    }
}

My question is, why does the view or any other view above RegistrationView need this object too and how do I save me from that work. I tried to make progress private but that doesn't work. I am defining the class and all other things in this view and I only need it for itself and the child of a child.

P.S. is there a better methode for observable objects? For example when I need the value in a main view and can change it in a child.child.child.view I have to pass it all the way down. And that seems kind of unnecessary work.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Tim4497
  • 340
  • 3
  • 19

1 Answers1

1

If you're not going to use it in parent view then just use locally as StateObject

struct RegistrationView: View {
    @StateObject var progress = Progress()    // << here !!

    // ... other code
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • okay my mistake was to use `@ObservedObject var progress: Progress` instead of `@ObservedObject var progress = Progress()` – Tim4497 Nov 06 '20 at 12:46