[SOLVED] Passing variable from view inside the class ObservableObject?

Issue

i got this struct

struct Calendar: View {
   @State private var selectDate = Date()
        var body: some View {
// my code 
}
Class fetchmydate: ObservableObject {
func fetchmydata (){
// i want to pass selectDate to here in "dd-mm-yyyy" format as string 
}
}
}

the idea i want to pass the selectdate from the view into observedobject class and not vice versa, but in this format "dd-mm-yyyy" and as a string. and if i don’t pass this selected date it says it can’t read the selected date inside the function.

i know it is somehow weird question but if it can’t be done in logic (passing) then what do you suggest to pass the date data and thank you alot my friends.

Solution

What are you trying to achieve is not something unheard of, is just easier to pass the entire logic to the viewModel, I believe you are looking for this:

The view:

struct ViewDate: View {
@State private var date = Date()
var myviewModel = viewModel()

var body: some View {

    DatePicker(selection: $date, displayedComponents: .date) {
        Text("Select your date")
        
    }
    .datePickerStyle(.wheel)
    .onChange(of: self.date) { newDate in
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        let stringDate = dateFormatter.string(from: newDate)

        myviewModel.fetchmydata(selectedDate: stringDate)
    }

   
}
}

The "View Model"

class viewModel: ObservableObject {

init() {}

func fetchmydata (selectedDate: String) {
    
// i want to pass selectDate to here in "dd-mm-yyyy" format as string
    print(selectedDate)
}

}

Answered By – Guillermo Jiménez

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.