Swift UI - How to access a @State variable externally?

I have ContentView.swift

struct ContentView: View {
    @State var seconds: String = "60"

    var body: some View {
        TextField("60", text: $seconds)
    }
    
    func getSeconds() -> String {
        return $seconds.wrappedValue;
    }
}

And AppDelegate.swift

class AppDelegate: NSObject, NSApplicationDelegate {
    var contentView = ContentView()

    ...
    
    func launchTimer() {
        print(contentView.getSeconds())
        let timer = DispatchTimeInterval.seconds(Int(contentView.getSeconds()) ?? 0)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + timer) {
            self.launchTimer()
        }
    }
    
    ...
}

contentView.getSeconds() always returns 60, even if I modify the value of the TexField in my content view (by manually typing in the text field).

How does one get the wrapped value/real value of a state variable from the app delegate?

1 answer

  • answered 2021-09-21 16:34 keyvan yaghoubian

    add a variable to appDelegate

    var seconds : Int? 
    

    then do this in your contentView :

        .onChange(of: seconds) { seconds in
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
            appDelegate.seconds = seconds
        }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum