简体   繁体   English

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

[英]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.我想将视图中的 selectdate 传递到 observedobject class 中,而不是相反,但以这种格式“dd-mm-yyyy”并作为一个字符串。 and if i don't pass this selected date it says it can't read the selected date inside the function.如果我没有通过这个选定的日期,它会说它无法读取 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:您想要实现的目标并非闻所未闻,只是更容易将整个逻辑传递给 viewModel,我相信您正在寻找这个:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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