How to bind SWIFTUI Button action to viewmodel action or method

Viewed 2432

I am trying to bind swiftui button action and getting the error like Cannot convert value of type 'Binding<() -> ()>' to expected argument type '() -> Void'

In View

Button(action : $viewModel.action ) {
                        Text("Login")
                    }

In ViewModel

class LoginViewModel: ObservableObject {
    
    @Published var userid = ""
    @Published var password = ""
    @Published var selection : Int? = 0
    //@Published var action : () -> void = {}
    func action()  {
        
    }
    
}
1 Answers

You don't need binding in Button action,

Button(action : viewModel.action ) {     // << no $ here !!
                        Text("Login")
                    }

everything else should be fine.

Related