iosswiftuiwatchoswidgetkitmacos-sonoma

How to remove padding around the content view and let the content view fill the entire area in Widget iOS 17+ and MacOS Sonoma?


I tried using .ignoresSafeArea() , but did not work.

There were not a padding in iOS 16 and early versions around the content view.

struct CommonDailyEyeTipsWidget: Widget {
    let kind: String = "CommonDailyEyeTipsWidget"

    init() {
        //setup firebase
        FirebaseApp.configure()
    }
    
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            Rectangle()
                .foregroundStyle(Color.primary)
                .ignoresSafeArea() // Does not work
                .containerBackground(.accent, for: .widget)
            
        }
        .contentMarginsDisabled()
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
    }
}

enter image description here


Solution

  • Yes, Safe areas in widgets have been replaced by the use of content margins. This means that modifiers like ignoresSafeArea no longer have any effect in widgets.

    you can still achieve this same effect by adding the contentMarginsDisabled modifier to your widget configuration.

    struct CommonDailyEyeTipsWidget: Widget {
        let kind: String = "CommonDailyEyeTipsWidget"
    
        init() {
            //setup firebase
            FirebaseApp.configure()
        }
        
        var body: some WidgetConfiguration {
            StaticConfiguration(kind: kind, provider: Provider()) { entry in
                Rectangle()
                    .foregroundStyle(Color.primary)
                    .containerBackground(.accent, for: .widget)
            }
            .contentMarginsDisabled() // Here
            .configurationDisplayName("My Widget")
            .description("This is an example widget.")
        }
    }
    

    NOTE: for any content which should remain within the default content margins, simply add padding back in. You can use the widgetContentMargins environment variable to get the default margins for the current environment.

    Ex:

    struct CommonDailyEyeTipsWidgetEntryView : View {
        @Environment(\.widgetContentMargins) var margins
        
        var entry: Provider.Entry
        
        var body: some View {
            Rectangle()
                .foregroundStyle(Color.primary)
                .padding(margins) // If you want a margin 
        }
    }
    

    Content Margin

    Content margin

    Content margins are padding which is automatically applied to your widget's body, preventing your content from getting to close to the edge of the widget container. These margins may be larger or smaller, depending on the environment where your widget is being shown.