今是昨非

今是昨非

日出江花红胜火,春来江水绿如蓝

Xcode15 Widget Compatibility

Background#

After upgrading to Xcode15, when running widgets, you may encounter the WIDGET_BACKGROUND_API_ADOPTION_PROMPT prompt, as shown in the following image:

image

Solution#

Create View_Extensions.swift with the following code:

import SwiftUI

extension View {
    @ViewBuilder func adoptableWidgetBackground(_ color: Color) -> some View {
        if #available(iOS 17.0, *) {
            containerBackground(for: .widget) { color }
        } else {
            background(color)
        }
    }
}

Then, in XXXLineProvider, find ZZZ_WidgetEntryView: View and modify it as follows:

struct ZZZ_WidgetEntryView: View {
    var body: some View {
        ...
        // Add the following code
        .adoptableWidgetBackground(Color.clear)
    }
}

After running again, you will find that this prompt has disappeared and the widget can be displayed. However, there is still an issue - if the widget background is an image, you will notice a white border around it. The solution is as follows: create WidgetConfiguration_Extensions.swift:

import SwiftUI

extension WidgetConfiguration {
    func adoptableWidgetContentMargin() -> some WidgetConfiguration {
        if #available(iOSApplicationExtension 15.0, *) {
            return contentMarginsDisabled()
        } else {
            return self
        }
    }
}

Then, in XXXLineProvider, find ZZZWidget: Widget and modify it as follows:

struct ZZZWidget: Widget {
    public var body: some WidgetConfiguration {
        IntentConfiguration(...) { entry in
            ...
        }
        .configurationDisplayName("displayName")
        .supportedFamilies([WidgetFamily.systemMedium])
        // Add the following property setting
        .adoptableWidgetContentMargin()
    }
}

This will resolve the issue.

Reference#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.