Home > Back-end >  SwiftUI: How to update button state from view model
SwiftUI: How to update button state from view model

Time:07-24

I want to enable and disable another button by updating the state variable in my view model. However, the other button is not activated. What am I doing wrong?

This is my code:

struct ContentView: View {
@State var viewModel = ViewModel()


var body: some View {
    VStack {
        Button(action: {
            viewModel.enableButton()
        }){
            Text("Activate other button")
        }
        
        Button(action: {
            /// code
        }){
            Text("To be activated...")
        }.disabled(viewModel.buttonDisabled)
    }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class ViewModel: ObservableObject {

    @State var buttonDisabled = true

    func enableButton() {
       buttonDisabled = false
    }

}

CodePudding user response:

Small mistake. You are supposed to use @Published in your view model and @ObservedObject in your view.

Modified code:

struct ContentView: View {
@ObservedObject var viewModel = ViewModel() //modified

var body: some View {
VStack {
    Button(action: {
        viewModel.enableButton()
    }){
        Text("Activate other button")
    }
    
    Button(action: {
        /// code
    }){
        Text("To be activated...")
    }.disabled(viewModel.buttonDisabled)
}
}
}

class ViewModel: ObservableObject {

@Published var buttonDisabled = true //modified

func enableButton() {
   buttonDisabled = false
}

}

CodePudding user response:

Not a State, but StateObject, because your ViewModel is a ObservableObject class

struct ContentView: View {
@StateObject var viewModel = ViewModel()  // << here !!

// ...

}
  • Related