【问题标题】:Show SwiftUI Dialog box on top of UIKit View在 UIKit 视图顶部显示 SwiftUI 对话框
【发布时间】:2023-01-05 22:06:19
【问题描述】:

SwiftUI 的新手在这里。我试图在现有 UIKit 视图之上显示一个内置于 SwiftUI 中的对话框。这个想法是为了能够看到 SwiftUI 对话框背后的 UIKit 视图的内容(就像警报对话框的默认行为)。但是不管我怎么尝试,我都看不到 UIKit 视图的内容。这甚至可以实现吗?

我想要一个以某种方式调整背景不透明度的警报样式对话框,以查看 UIKit 视图的内容。这是我的输出: alert content hides the view behind it

有人可以指出我正确的方向吗?

这是我的代码示例:

SwiftUI 中的对话框:

struct TestDialog: View {
    
    var body: some View {
        ZStack {
            Rectangle().foregroundColor(Color.black.opacity(0.5))
                .frame(maxHeight: .infinity)
            
            VStack(alignment: .center, spacing: 15) {
                Text(.init("Some Text"))
                    .multilineTextAlignment(.center)
                    .padding()
                Button(action: {}) {
                    Text("Button 1")
                        .padding(10)
                }
                Button(action: {}) {
                    Text("Button 2")
                        .padding(10)
                }
            }
            .padding()
            .background(
              RoundedRectangle(cornerRadius: 12)
                .foregroundColor(.white))
            .padding(40)
        }
    }
}

以及在我的viewDidLoad()中调用的方法:

func showTestDialog() {
        let testView = TestDialog()
        let testchildView = UIHostingController(rootView: testView)
        
        addChild(testchildView)
        let titleBarOffset: CGFloat = 11
        testchildView.view.frame = view.frame.offsetBy(dx: 0, dy: -titleBarOffset)
        view.addSubview(testchildView.view)
        testchildView.didMove(toParent: self)
    }

【问题讨论】:

  • 您是否尝试将UIHostingController 的背景设置为clear
  • 哇,谢谢你的提示。成功了!我设置了testchildView.view.backgroundColor = .clear,它开始按预期出现。不过我想知道,有没有办法在 SwiftUI 视图中处理这个问题?

标签: swiftui uikit


【解决方案1】:

为了看穿 SwiftUI,您需要确保它的宿主视图具有透明背景:

testchildView.view.backgroundColor = .clear

这必须在主机视图级别完成,因为它是父级/容器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    相关资源
    最近更新 更多