【问题标题】:How to make Hosting View transparent in SwiftUI?如何在 SwiftUI 中使 Hosting View 透明?
【发布时间】:2021-10-30 09:33:45
【问题描述】:

我需要我的应用程序中的几乎所有视图都具有透明背景,包括默认情况下具有不透明背景的 TabView 和 NavigationView。通过将以下代码添加到我的.onAppear() 函数中,我基本上能够通过将 UIView 的默认背景设置为.clear 来完成。

UIView.appearance().backgroundColor = .clear

但是,虽然这适用于大多数视图,但我注意到 Hosting View 仍保留其不透明背景。所以我想知道如何才能使这个视图的背景透明?

Here 是在将.clear 应用于 UIView 背景时对有问题视图的视图层次结构捕获。虽然我实际上已经设法使用Introspect 删除了这些视图的背景,但在实际设备上运行我的应用程序时,这种解决方法似乎无法正常工作(一些视图保持不透明,其他视图由于某种原因仅在切换后变得透明运行时的配色方案)。那么我还能如何做到这一点呢?

任何帮助或建议将不胜感激!

【问题讨论】:

  • 试试hostingController.view.isOpaque = falsehostingController.view.backgroundColor = UIColor.clear
  • @RTXGamer 我还没有尝试过——我在哪里可以访问托管视图控制器?
  • 不确定您如何在代码库中使用 HostingContoller,但添加了一个示例来给您一个想法。

标签: swift view swiftui uiview background


【解决方案1】:

这将添加带有clear 背景的 SwiftUI 视图作为子视图控制器:

struct SwiftUIView: View {
    var body: some View {
        VStack{
            HStack{
                Text("Testing Hosting VC")
            }
        }.font(.headline)
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blue
        
        let hostingController = UIHostingController(rootView: SwiftUIView())
        hostingController.view.isOpaque = false
        hostingController.view.backgroundColor = UIColor.clear
        addChild(hostingController)
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(hostingController.view)
        hostingController.view.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        hostingController.view.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        hostingController.didMove(toParent: self)
    }
}

【讨论】:

  • 哦,好的。我只是使用 TabView 和 NavigationView 默认使用的视图控制器。有什么办法可以修改它们,还是我唯一的选择是从头开始创建自定义 TabView 和 NavigationView?
猜你喜欢
  • 2021-01-19
  • 2022-08-12
  • 2023-01-27
  • 2021-08-25
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
相关资源
最近更新 更多