Home > OS >  iOS SwiftUI - Cannot convert value of type ObservedObject
iOS SwiftUI - Cannot convert value of type ObservedObject

Time:08-02

I have this view:

struct CreateAccountButton : View {
    
    @Binding var viewRouter: ViewRouter

    var body: some View{
        Button(action: {
            withAnimation {
                viewRouter.currentPage = .register
            }
            
        }) {
            
            Text("create_account")
                .padding(.vertical)
                .frame(maxWidth: .infinity)
                .foregroundColor(Color("ColorText"))
                .overlay(
                    RoundedRectangle(cornerRadius: 5)
                        .stroke(Color.white, lineWidth: 0))
                
        }
        .background(Color("BtnGreenBG"))
        .frame(minWidth: 0, maxWidth: .infinity)
        .cornerRadius(5)
        .padding(.top, 12)
    }
}

and I need to pass the viewRouter which I created in the mainview:

@StateObject var viewRouter: ViewRouter

I tried:

CreateAccountButton(viewRouter: $viewRouter)

and get:

Cannot convert value of type 'ObservedObject<ViewRouter>.Wrapper' to expected argument type 'Binding<ViewRouter>'

I'm new to ios/swiftui and don't understand this error.

Based on this answer:

How we can convert value of type ObservedObject to Binding in SwiftUI?

I changed

@Binding var viewRouter: ViewRouter

to

@ObservedObject var viewRouter: ViewRouter

inside CreateAccountButton and it's still not working

SwiftUI/Swift is an unintuitive nightmare compared to Kotlin :(

Please help

CodePudding user response:

The ObservableObject is a reference type so we can just pass it by reference directly, binding is not needed.

struct CreateAccountButton : View {
    
    let viewRouter: ViewRouter     // << regular property

// if needed to observe it internally, ie. body (not closures) 
// contains router's property usage

//  @ObservedObject var viewRouter: ViewRouter


// ...

and call

CreateAccountButton(viewRouter: viewRouter) // inject reference

CodePudding user response:

Don’t pass the whole object, instead pass only a specific data of your vm.

CreateAccountButton(viewRouter: $viewRouter.currentPage)

And

@Binding var currentPage: Bool 

In your CreateAccountButton.

  • Related