Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing variables between ViewController and SwiftUI

This is my first time working in Xcode and I am building an app using Storyboards/View Controllers. However, I have a page I want to display using SwiftUI, which I am doing through a host controller. I want to be able to assign a value to a variable in my ViewController code and then access this value in my swiftUI ContentView file. I feel like there should be a simple solution, but I can't seem to find a way to share data between the two. Thank you for any help.

like image 367
rachela Avatar asked May 22 '26 04:05

rachela


1 Answers

Here is a simple method to see how to pass data to SwiftUI View from UIKit UIViewController. Here I'm passing a simple text setting it in the initializer of ContentView and presenting the UIHostingController on ViewController. Here is the code:

import UIKit
import SwiftUI
import PlaygroundSupport

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(action))
    }

    @objc func action() {
        let contentView = ContentView(text: "My Text")
        let viewController = UIHostingController(rootView: contentView)
        present(viewController, animated: true)
    }
}


struct ContentView: View {

    var text: String

    var body: some View {
        Text(text)
    }
}

PlaygroundPage.current.setLiveView(UINavigationController(rootViewController: ViewController()))
PlaygroundPage.current.needsIndefiniteExecution = true

You can copy/paste this code on your playground to see how it works.

like image 120
Frankenstein Avatar answered May 23 '26 23:05

Frankenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!