首页 > 解决方案 > 将 SwiftUI 视图与 UIView 一起使用的方法

问题描述

我正在使用使用UIKit. 它的 API 需要一个 UIView 的引用。

如何在 SwiftUI 中使用这个库?以及如何将 SwiftUI 视图转换为 UIView?

我试过创建一个UIViewRepresentable这样的:

struct SomeView: UIViewRepresentable {

    let contentViewController: UIViewController

    init<Content: View>(contentView: Content) {
        self.contentViewController = UIHostingController(rootView: contentView)
    }

    func makeUIView(context: Context) -> UIKitView {

        // Whatever I do here doesn't work. Frame is always 0

        contentViewController.loadViewIfNeeded() 
        contentViewController.view.setNeedsDisplay()
        contentViewController.view.layoutIfNeeded()

        print(contentViewController.view.frame)

        let uikitView = UIKitView()
        uikitView.show(contentViewController.view)
        return popover
    }

    func updateUIView(_ uiView: UIKitView, context: Context) {
    }
}

标签: uikitswiftui

解决方案


推荐阅读