繁体   English   中英

SwiftUI中如何让Hosting View透明化?

[英]How to make Hosting View transparent in SwiftUI?

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

UIView.appearance().backgroundColor = .clear

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

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

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

这将添加 SwiftUI 具有clear背景的视图作为子视图 controller:

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)
    }
}

我发现创建一个简单的UIHostingController子类更容易、更直接:

import SwiftUI

public final class TransparentHostingController<Content: View>: UIHostingController<Content> {
    public override func viewDidLoad() {
        super.viewDidLoad()
        view.isOpaque = false
        view.backgroundColor = .clear
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM