[SwiftUI] Widget Padding 없애기

 

기존의 방법으로 Widget에 Background를 적용하려고 하면, 제대로 적용되지 않고 이상한 padding이 적용되어 있다.

 

 

 

이런 식으로!

 

너무 이상해 보여서 여러 방법을 찾아보다가 괜찮은 글을 발견해서~~! 블로그에도 기록해놓으려고 한다.

 

찾아보니 Xcode15 / iOS 17부터는 Widget에 contentMargin이 기본으로 적용되어 있어 이를 해제해 주는 것이 필요하다.

 

그 방법으로는. .. .

 

struct CoinWidgets: Widget {
    let kind: String = "CoinWidgets" // 위젯의 고유한 문자열
    
    var body: some WidgetConfiguration {
        AppIntentConfiguration(kind: kind, intent: ConfigurationAppIntent.self, provider: Provider()) { entry in
            CoinWidgetsEntryView(entry: entry)
                .containerBackground(.fill.tertiary, for: .widget)
        }
        .configurationDisplayName("관심있는 코인")
        .description("실시간 시세를 확인하세요!")
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .accessoryCircular, .accessoryInline, .accessoryRectangular])
        .contentMarginsDisabled()
    }
}

 

 

위와 같이 WidgetConfiguration에서 직접 `.contentMarginsDisabled()`를 적용해 줘도 되구

아님 WidgetConfiguartion의 extension에 아래와 같은 함수를 구현해 주면 추후 프로젝트 컴파일 시 자동으로 적용된다.

 

 

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

 

 

 

 

그럼 이제 원하는대로 배경색이 들어간다!!

짱.

 

 

 

 

 

참고 자료

https://developer.apple.com/forums/thread/731423

 

Xcode 15 + iOS 17 adds extra paddi… | Apple Developer Forums

This is probably a newbie type question, but is it possible to fix this in an Xcode 14 build? The extension does work well on a build in Xcode 15, but we're not supposed to submit Xcode 15 builds to the App Store currently, right (but maybe this is a bad a

developer.apple.com

https://developer.apple.com/documentation/swiftui/widgetconfiguration/contentmarginsdisabled%28%29

 

contentMarginsDisabled() | Apple Developer Documentation

Disable default content margins.

developer.apple.com

https://developer.apple.com/videos/play/wwdc2023/10027/

 

Bring widgets to new places - WWDC23 - Videos - Apple Developer

The widget ecosystem is expanding: Discover how you can use the latest WidgetKit APIs to make your widget look great everywhere. We'll...

developer.apple.com