如何在SwiftUI中使Hosting View透明?

4

我希望我的应用程序中几乎所有的视图都具有透明背景,包括默认具有不透明背景的TabView和NavigationView。我已经通过将UIView的默认背景设置为.clear并在.onAppear()函数中添加以下代码来完成大部分工作。

UIView.appearance().backgroundColor = .clear

然而,虽然这对大多数视图有效,但我注意到 Hosting View 仍保留其不透明的背景。因此,我想知道如何使此视图的背景透明?这里 是一个有问题的视图层次结构捕获,当应用 .clear 到 UIView 背景时。虽然我已经成功使用Introspect删除了这些视图的背景,但是当在实际设备上运行我的应用程序时,此解决方法似乎无法正常工作(某些视图仍然不透明,其他一些原因只在运行时切换颜色方案后变为透明)。那么我还能用什么方法来完成这个任务呢?任何帮助或建议都将不胜感激!

尝试将 hostingController.view.isOpaque = falsehostingController.view.backgroundColor = UIColor.clear 添加到代码中。 - RTXGamer
@RTXGamer 我还没有尝试过那个,我可以在哪里找到主机视图控制器? - CodeSwift
不确定你在代码库中如何使用HostingContoller,但我添加了一个示例来给你一个想法。 - RTXGamer
@CodeSwift你有找到解决方案吗?我遇到了一个我认为非常相似的问题。 - Brandon Slaght
@BrandonSlaght 抱歉回复晚了!很遗憾,目前还没有。除非他们改变这一点,否则我想你可能需要尝试将一个 UIView 包装起来。 - CodeSwift
2个回答

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? - CodeSwift

-1

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

import SwiftUI

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

1
这是如何工作的?view 是从哪里来的?这似乎无法按照这里所示进行编译。 - viraptor
@viraptor,你能提供具体的编译错误吗? UIHostingController继承自UIViewController,因此它具有一个视图。https://developer.apple.com/documentation/swiftui/uihostingcontroller - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接