在@ObservableObject 中时如何从结构中读取 属性

How to read property from a struct when being in @ObservableObject

我不知道如何从 Observable Object.

的 class 中读取结构中的 属性

上下文:

我正在尝试构建一个包含 2 个视图的应用程序:

问题是我在 'getJoke' [=51] 的 ObservableObject 中引用的 'currentDate' 属性(保存所选日期的值) =] 不会在用户选择不同的日期时更新。它总是在今天而不是在用户选择的日期获取笑话。

代码如下:

import SwiftUI
import grpc

struct CustomDatePicker: View {
    
    @State var currentDate: Date
    @State var dailyJokePopUp = false

  //some code here
                        // When the user selects the date, currentDate property changes to the selected date
                        .onTapGesture {
                            currentDate = value.date
                        }

  //  Getting selected day for displaying in dailyJokePopUp
    func getCurrentDay()->String{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy"
        let date = dateFormatter.string(from: currentDate)
        return date
    }

    
    class getJoke : ObservableObject {
        
        @Published var data = [JokeX]()
        @Published var noData = false
        @Published var currentDate = Date()
        
    //some code here including adding SnapShotListener
                
                let callCDP = CustomDatePicker(currentDate: currentDate).getCurrentDay()
                if id == callCDP {
                    self.data.append(joke_text_imported)}

                }
            }

    }
    }
    
import SwiftUI

struct dailyJokePopUp: View {
    
    @Binding var show: Bool
    @ObservedObject var Jokes = getJoke()    

    var currentDate: Date = Date()
    
 //some code here

  ForEach(self.Jokes.data){i in
  Text(i.joke_text)
  }

 //some code here
}

我怀疑我声明属性的方式有问题。我尝试了各种包装器(@Binding、@StateObject),但我感到困惑并且没有用。希望有好心人帮我解决问题

视图模型

class getJoke: ObservableObject {
  @Published var currentDate = Date()
}

可以更改传递数据的视图

struct CustomDatePicker: View {

  @Binding var currentDate: Date

  var body: some View{
      VStack {
          DatePicker(selection: $currentDate, displayedComponents: .date){
                Text("Select your date")
          }
          .datePickerStyle(.compact)
      }
  }
}

然后把所有东西放在一起[=13​​=]

    struct ContentView: View {
    
    @StateObject var vm = getJoke()
    
    var body: some View {
        VStack(spacing: 40) {
            CustomDatePicker(currentDate: $vm.currentDate)
            Button {
                print(vm.currentDate)
            } label: {
                Text("Show selected date")
            }

        }
    }
}