Why is a @State property in SwiftUI not readable from outside?

213 Views Asked by At

I only wan't to read, not to change the value of a @State property of my SwiftUI view. In .onAppear the value will be changed but that change is not visible to the outside world. Why?

class MyController : UIHostingController<SwiftUIView> {
    public func getText() -> String? {
        rootView.text
    }
}

struct SwiftUIView: View {
    @State public var text: String?
    
    var body: some View {
        Text(text ?? "Hello World")
            .background(Color.red)
            .onAppear {
                text = "so und so"
            }
    }
}

class ViewController: UIViewController {
    var subs = Set<AnyCancellable>()
    var vc: MyController!
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        vc = MyController(rootView: SwiftUIView())
        vc.view.backgroundColor = UIColor.green
        
        addChild(vc)
        view.addSubview(vc.view)
        vc.view.frame = view.bounds
        
        print("text = \(vc.getText() ?? "nil")")
        
        Timer.publish(every: 1, on: .current, in: .default)
            .autoconnect()
            .receive(on: RunLoop.main)
            .sink { _ in
                print("text = \(self.vc.getText() ?? "nil")")
            }
            .store(in: &subs)
    }
}

I know that @State and @ObservedObject exists. @State is for internal managed, @ObservedObject for external managed states. But I don't want to change the value, I only wan't to read. But why is that not possible and why is the return value nil? That's simply wrong. It's no timing problem.

1

There are 1 best solutions below

0
On

Declare the value in the ViewController and pass it down to the SwiftUIView.