ios - 将数据从 SwiftUI View 传递到 UIViewController

标签 ios swift uiviewcontroller storyboard swiftui

我一直在测试 SwiftUI 看看我能走多远。现在,我想知道是否可以从 SwiftUI View 传递字符串直接到 UIViewController .我想用 UILabel 显示这个字符串. UILabel这是我的 Storyboard上的全部内容。

以下是我的 View Controller ( UIViewController )。

import UIKit
import SwiftUI

class HomeViewController: UIViewController {
    var message = String()

    @IBOutlet weak var messageLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        messageLabel.text = message
    }
}

struct HomeViewControllerRepresentation: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) -> HomeViewController {
        UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController
    }

    func updateUIViewController(_ uiViewController: HomeViewController, context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) {

    }
}

我的 SwiftUI View以下是。
import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: HomeViewControllerRepresentation(message: "GGG")) { // Error
                    Text("Tap me")
                }
            }
            .navigationBarTitle("")
            .navigationBarHidden(true)
        }
    }
}

我希望我可以只传递一个带有 HomeViewControllerRepresentation 的字符串。但它不会工作。是否有一种从 SwiftUI 传递数据的简单方法 ViewUIViewController ?谢谢。

最佳答案

UIViewControllerRepresentable不是代理,而是包装器,所以一切都应该手动传输,比如

struct HomeViewControllerRepresentation: UIViewControllerRepresentable {
    var message: String

    func makeUIViewController(context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) -> HomeViewController {
        let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController
        controller.message = self.message
        return controller
    }

    func updateUIViewController(_ uiViewController: HomeViewController, context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) {

    }
}

关于ios - 将数据从 SwiftUI View 传递到 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62443417/

相关文章:

ios - semaphore_wait_trap 阻塞 UI

ios - 如何从 UIViewcontroller 加载 UIView?

ios - 应用内购买 - 空产品列表

ios - 替换 CLLocationManager 的 "purpose"属性

ios - 测试 iOS 应用程序时,为什么不报告所有应用程序崩溃?

ios - iOS 的分析工具不起作用

ios - 为 View Controller 设置 socket /操作

ios - PhoneGap CLI "cordova build ios"失败

ios - 如何使用 IOS 中的 UIActivityViewController 将我的应用程序中的视频分享到 YouTube 和 Instagram 应用程序?

ios - 访问 swift 类