How to initialize a view with a stateobject as a parameter?

Viewed 3712
struct ProfileEditView: View {
    @ObservedObject var viewModel: UsersViewModel
    @StateObject var auth: Authenticator

    @State var showingImageEditor: Bool = false

    init(_ viewModel: UsersViewModel, _ auth: Authenticator) {
    
        self.viewModel = viewModel
        self.auth = auth
    
        UITableView.appearance().backgroundColor = UIColor.clear
        UITableViewCell.appearance().selectionStyle = .none
    }

    var body: some View { }
}

I am trying to manually intialize a view that takes a StateObject as a parameter. I am getting an error: Cannot assign to property: 'auth' is a get-only property. What is the proper way to write the initializer?

1 Answers

I can't fully reproduce your code without your definitions of Authenticator and UsersViewModel, but I got it to compile:

class UsersViewModel: ObservableObject {}
class Authenticator: ObservableObject {}

struct ProfileEditView: View {
    @ObservedObject var viewModel: UsersViewModel
    @StateObject var auth: Authenticator

    @State var showingImageEditor: Bool = false

    init(_ viewModel: ObservedObject<UsersViewModel>, _ auth: Authenticator) {

        _viewModel = viewModel
        _auth = StateObject(wrappedValue: auth)

        UITableView.appearance().backgroundColor = UIColor.clear
        UITableViewCell.appearance().selectionStyle = .none
    }

    var body: some View {
        Text("something")
    }
}

These are the key changes:

init(_ viewModel: ObservedObject<UsersViewModel>, _ auth: Authenticator) {
    _viewModel = viewModel
    _auth = StateObject(wrappedValue: auth)

If you don't understand my changes you should google

"swift property wrappers"

to get a better understanding of what property wrappers are and how to use them.

Related