这是一个简单的方法来查看如何将数据传递给SwiftUI Viewfrom
UIKit UIViewController。在这里,我text在 的初始值设定项中传递一个简单的设置ContentView并呈现UIHostingControlleron ViewController。这是代码:
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
Run Code Online (Sandbox Code Playgroud)
您可以在您的 Playground 上复制/粘贴此代码以查看它是如何工作的。