请采用containerBackground API

Mik*_*e B 5 ios swift widgetkit watchos swiftui

更新到 Xcode beta 并构建/运行我的应用程序后,我开始在所有小部件上收到错误“请采用 containerBackground API”,并且我找到了一篇文章,其中提供了适应 iOS 14-16 的解决方案

import Foundation
import SwiftUI


extension View {
    @ViewBuilder
    func widgetBackground() -> some View {
        let gradient = LinearGradient(gradient: Gradient(colors: [Color("LightBlue"), Color("DarkBlue")]), startPoint: .topLeading, endPoint: .bottomTrailing)
        
        if #available(watchOS 10.0, iOSApplicationExtension 17.0, iOS 17.0, macOSApplicationExtension 14.0, *) {
            self.containerBackground(gradient, for: .widget)
        } else {
            self.background(gradient)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我将其添加到我的 ZStack 中作为小部件,但它什么也没做。采用containerBackground API 时我仍然遇到相同的错误。我究竟做错了什么?

Mon*_*ona 2

您需要将 .containerBackground(.....) 添加到所有小部件视图中,无论它们以前是否有 .background