UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Why is disabled not working with a view model?

Forums > SwiftUI

For some reason, my "Add Event" button is always disabled and I can't figure out why. What am I missing here?

struct AddEventView: View {
    @Environment(\.presentationMode) var presentationMode

    @State private var addEventVM = AddEventVM()

    var body: some View {
        VStack {
            TextField("Enter name", text: $addEventVM.name)
            Button("Add Event") {
                self.addEventVM.saveEvent()
                self.presentationMode.wrappedValue.dismiss()
            }.disabled(self.addEventVM.name == "")
            .padding()
        }
    }
}

class AddEventVM {
    var name: String = ""

    func saveEvent() {
        CoreDataManager.shared.saveEvent(name: self.name)
    }
}

This code is working perfectly fine without using a view model.

struct AddEventView: View {
    @Environment(\.presentationMode) var presentationMode

    @State private var name = ""

    var body: some View {
        VStack {
            TextField("Enter name", text: $name)
            Button("Add Event") {
                self.addEventVM.saveEvent()
                self.presentationMode.wrappedValue.dismiss()
            }.disabled(self.name == "")
            .padding()
        }
    }
}

2      

hi Mike,

make the view model conform to ObservableObject, make its name propertery @Published, and then change the @State property wrapper to @ObservedObject on the view model.

@ObservedObject private var addEventVM = AddEventVM()

that should do it. hope it helps.

DMG

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.