首页 > 解决方案 > UIHostingViewController 背景颜色显示

问题描述

我正在通过 SwiftUI 视图显示 UIViewController,如下所示:

@available(iOS 13, *)
struct WelcomeNavView: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<WelcomeNavView>) -> UINavigationController {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let navVc = storyboard.instantiateViewController(withIdentifier: "welcomeNav") as! UINavigationController
        return navVc
    }

    func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<WelcomeNavView>) {
    }
}

然后我从 ViewController 中呈现它,如下所示:

self.viewController?.present(style: .fullScreen) {
    WelcomeNavView()
}

但是,它并没有占据整个屏幕,并且 UIHostViewController 颜色显示在顶部和底部:

在此处输入图像描述

如何更改 UIHostingViewController 视图的颜色。或者扩展它所持有的视图以占据整个屏幕?

标签: swiftui

解决方案


这是解决方案,我遇到了类似的问题,其中我必须将托管视图控制器的背景设置为清晰。

显然hostingVC和hostingVC.view的rootView(可能是我们的SwiftUI View)是不一样的。

所以这将允许您更改为背景颜色。

hostingVC.view.backgroundColor = .clear

当然使用任何颜色代替“.clear”。

请记住,相应地更改作为 rootView 传递给 hostingVC 的 SwiftUI 视图的颜色,大部分情况下要清楚,所以它不会显示在上面设置的颜色上。

Your_SwiftUI_View.background(Color.clear)

推荐阅读