如何将 SWIFTUI 按钮操作绑定到视图模型操作或方法

Pra*_*hap 5 ios two-way-binding swiftui

我正在尝试绑定 swiftui 按钮操作并收到类似错误Cannot convert value of type 'Binding<() -> ()>' to expected argument type '() -> Void'

在视野中

Button(action : $viewModel.action ) {
                        Text("Login")
                    }
Run Code Online (Sandbox Code Playgroud)

在视图模型中

class LoginViewModel: ObservableObject {
    
    @Published var userid = ""
    @Published var password = ""
    @Published var selection : Int? = 0
    //@Published var action : () -> void = {}
    func action()  {
        
    }
    
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 6

您不需要在按钮操作中绑定,

Button(action : viewModel.action ) {     // << no $ here !!
                        Text("Login")
                    }
Run Code Online (Sandbox Code Playgroud)

其他一切都应该没问题。