Home > database >  Working with SwiftUI views and StateObject in packages
Working with SwiftUI views and StateObject in packages

Time:11-04

I created a SwiftUI view and ObservableObject in a package like this one:

struct CustomView: View {
    
    @StateObject
    var viewModel: CustomViewModel
    
    var body: some View {
        Text("Test")
    }
}


class CustomViewModel: ObservableObject {
    
    var folderName: String
    
    init(folderName: String) {
        self.folderName = folderName
    }
}

I'm using this like here:

struct ContentViewInsidePackage: View {
    var body: some View {
        CustomView(viewModel: CustomViewModel(folderName: "Winter"))
    }
}

How can I use the View and ObservableObject outside of the package?

The problem is when I'm using this view outside of the package then I need to declare everything public and I need a public init like here:

public struct CustomView: View {
    
    @StateObject
    var viewModel: CustomViewModel
    
    public init(viewModel: CustomViewModel) {
        // Compile Error: Cannot assign to property: 'viewModel' is a get-only property
        self.viewModel = viewModel
    }
    
    public var body: some View {
        Text("Test")
    }
}

public class CustomViewModel: ObservableObject {
    
    var folderName: String
    
    public init(folderName: String) {
        self.folderName = folderName
    }
}

Then I get the compile error: Cannot assign to property: 'viewModel' is a get-only property

How can I instantiate the ObservableObject with the values I want to inject?

CodePudding user response:

Try this:

public struct CustomView: View {
    
    @StateObject
    var viewModel: CustomViewModel
    
    public init(viewModel: CustomViewModel) {
        // Note the change on the below line:
        self._viewModel = StateObject(wrappedValue: viewModel)
    }
    
    public var body: some View {
        Text("Test")
    }
}

public class CustomViewModel: ObservableObject {
    
    var folderName: String
    
    public init(folderName: String) {
        self.folderName = folderName
    }
}
  • Related