从 class ObservableObject 内部的视图传递变量?

Passing variable from view inside the class ObservableObject?

我得到了这个结构

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

我想将 selectdate 从视图传递到 observedobject class 而不是相反,但以这种格式“dd-mm-yyyy”并作为字符串。如果我没有通过这个选定的日期,它说它无法读取函数内的选定日期。

我知道这是个奇怪的问题,但如果它不能在逻辑上完成(通过)那么你有什么建议来传递日期数据,非常感谢我的朋友们。

你想达到的目的不是闻所未闻,只是更容易将整个逻辑传递给 viewModel,我相信你正在寻找这个:

观点:

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

   
}
}

“视图模型”

class viewModel: ObservableObject {

init() {}

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

}