为什么 SwiftUI 中的 Today App Extension Widget 是白色的?

Why Today App Extension Widget in SwiftUI is white?

just like this

我的观点很简单:

Text("Testing Widget")

并尝试了这个:

VStack {
    Text("Testing Widget")
}
.background(Color(UIColor.clear))

什么也没发生:(.

刚刚为我找到了解决方案!

您必须将 UIHostingControllerviewbackgroundColor 设置为 .clear,然后它才会起作用。您不需要设置 SwiftUI 视图的背景颜色。

let hostingController = UIHostingController(rootView: SwiftUIView())

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    view.addSubview(hostingController.view)
    addChild(hostingController)
    hostingController.didMove(toParent: self)

    // You may want to add constraints

    hostingController.view.backgroundColor = .clear // <- IMPORTANT
}