SwiftUI 如何从另一个类访问 ContentView 变量

leo*_*oe1 5 variables class instance-variables swift swiftui

我是 SwiftUI 的新手。在尝试改进我的计时器应用程序时,我陷入了困境。

在我的 ContentView 中,我有两个 ObservedObjects:管理计时器功能的 Timer 对象和存储所有用户设置的 Settings 对象。我的目标是,如果用户更改切换设置,则会在 ContentView 类中定义的 MyTimer 实例中设置一个变量。

我的问题是我不知道如何从类设置访问该实例。

这可能是一个非常简单的解决方案,但是,我已经尝试让它工作很长一段时间了,但我运气不好。

感谢您的帮助!


struct ContentView: View {

    @ObservedObject var myTimer = MyTimer()
    @ObservedObject var settings = Settings()

...

 Toggle(isOn: self.$settings.muteInSilenceMode) {
        Text("Mute sound in silence mode")
                                    }
...

}

class Settings: ObservableObject {

...

    @Published var muteInSilenceMode: Bool = UserDefaults.standard.bool(forKey: "muteInSilenceMode"){
              didSet{
                  UserDefaults.standard.set(self.muteInSilenceMode, forKey: "muteInSilenceMode"

                  // I want to access the Timer object from here

              }
          }
...

}

Run Code Online (Sandbox Code Playgroud)

Kuh*_*ann 1

我不明白您的 Settings() 与您的问题有什么关系,但我认为您问题的答案如下所示:

struct ContentView : View {

    @ObservedObject var myTimer = MyTimer()
    @ObservedObject var settings = Settings()

    @State private var timer: Bool

    var body: some View {

        let toggleTimer = Binding<Bool> (
            get: { self.timer},
            set: { newValue in
                self.timer = newValue
                if self.timer {
                    myTimer.theVaribableYouWantToChange = true // Didn't know the name of your variable.
                } else {
                    // Whatever shall happen if the Toggle gets deactivated.
                }
        })

        return HStack {
            Toggle(isOn: toggleTimer) {Text("Activate") }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)