DEV Community

ochieng seth
ochieng seth

Posted on

How to bind a function from an ObservableObject in swiftui

my class contains a function,

class UserModel: ObservableObject {

  func fetchUser(){
    // code
  }
}
Enter fullscreen mode Exit fullscreen mode

i call this class in a struct

struct UserView: View {
  @StateObject var userModel = UserModel()
  @State var loading: Bool = false

  var body: some View {
    ButtonComponent(loading: $loading)
  }
}
Enter fullscreen mode Exit fullscreen mode

I would like to access the class in ButtonComponent just like i did with the loading variable by binding it.
The ButtonComponent is like this..

struct ButtonComponent: View {
  @Binding var loading: Bool

  var body: some View {
    Button(action: {loading.toggle()}){
      Text("Submit Button")
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Help on how to achieve this is appreciated

Latest comments (1)

Collapse
 
coucoseth profile image
ochieng seth

i found a fix
binding it in ButtonComponent just like i did for loading variable like so

@Binding var userMdl: UserModel
Enter fullscreen mode Exit fullscreen mode

Then in the UserView when calling the ButtonComponent i bind the userModel state object like so..

ButtonComponent(loading: $loading, userMdl: .constant(userModel))
Enter fullscreen mode Exit fullscreen mode