SwiftUI: Fatal Error: Accessing State<String> outside View.body"

I have a MainView, which is my rootViewController, in SwiftUI.

In there is a @State var myString : String that is bound to a Textfield.

Theres a button that presents a UIViewController "MyViewController" from the rootViewController when pressed.

The MyViewController has a delegate that calls a function delegateEnds in which I want to set the myString from the presentingViewController (line 11 of MyViewController.swift) to a certain value that a delegate (MyDelegate) delivers.

This is where the error is happening:


Thread 1: Fatal Error: Accessing State<String> outside View.body


How can I resolve this problem? My goal is to present the UiViewController and get a string result from it down to the MainView's myString variable that is bound to the Textfield, so that the TextField updates right away.


Since I can't change the @state variabe from outside the view appearently, is there any other way?


Thanks in advace!



MainView.swift:


struct MainView : View {
     @State var myString: String = ""

     var body: some View{
          VStack{
               
               TextField($myString)

               Button(action:{
                    let rootVC : UIViewController = UIApplication.shared.keyWindow!.rootViewController!
                    rootVC.present(MyViewController.init(), animated: true, completion: nil)
                    })
               }
}
}


MyViewController.swift:


class MyViewController : UIViewController , MyDelegate {

     override func viewDidLoad(){
     super.viewDidLOad()
     //...some delegatestuff
     }

     func delegateEnds(withResult result: String!){
          if let presenter = presentingViewController {
              let pres= presenter as! UIHostingViewController
              pres.rootView.myString = result.resultString
          }    
          self.dismiss(animated: true, coimpletion: nil) 
     }
}

I cannot test it, but I would try one of the following:

- send notification from MyViewController and have UIHostingViewController subscribe to it

and absolutely not sure it can work here…

- declare another var in MainView (not state) ;

- var transferString: String = ""

- have a didSet in transferString which updates myString

- change line 11 as

pres.rootView.transferString = result.resultString

Hey thanks a lot for the quick reply!

Unfortunately when I change the transferString in my ViewController the "didSet" is never called.

Guess I will try the notifications!

SwiftUI: Fatal Error: Accessing State&lt;String&gt; outside View.body"
 
 
Q