简体   繁体   中英

Passing variable from view inside the class ObservableObject?

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.

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)
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM