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