swiftuiwidgetkit

WidgetKit Background not filling all available space


I'm building a widget with WidgetKit.

On iOS 17 the background works fine, however, on any version below that (say 16), there are gaps on the vertical axis.

Here's the code that's causing this issue:

var body: some WidgetConfiguration {
    StaticConfiguration(kind: kind, provider: Provider()) { entry in
        let color = entry.widgetData.bgColor
        
        if #available(iOS 17.0, *) {
            homeWidgetEntryView(entry: entry)
                .containerBackground(.linearGradient(AnyGradient(Gradient(colors:  [color, color.lighten(percent: 5) , color.lighten(percent: 15)])), startPoint: .top, endPoint: .bottom), for: .widget)
        } else {
            homeWidgetEntryView(entry: entry)
            // this is the padding that's missing to fill the small widget's area, however this also streches the content to the edges
            //                    .padding(.vertical, 20)
            //                    .padding(.horizontal, 8)
                .background(LinearGradient(colors: [color, color.lighten(percent: 5) , color.lighten(percent: 15)], startPoint: .top, endPoint: .bottom))
        }
    }
    .supportedFamilies([.systemSmall])
}

Screenshot:

enter image description here


Solution

  • From the documentation for background(alignment:content:):

    Layers the views that you specify behind this view.

    It only fills the background of the view, so its size will exactly match the size of the view it's applied to. You need to use .frame(maxHeight: .infinity) for the modifier to fill the whole view:

    homeWidgetEntryView(entry: entry)
        .frame(maxHeight: .infinity)
        .background(LinearGradient(colors: [color, color.lighten(percent: 5) , color.lighten(percent: 15)], startPoint: .top, endPoint: .bottom))