Skip to content

Instantly share code, notes, and snippets.

@kylebshr
Last active June 6, 2023 00:18
Show Gist options
  • Save kylebshr/18ca3015ff742b64237a204f5b96cb3e to your computer and use it in GitHub Desktop.
Save kylebshr/18ca3015ff742b64237a204f5b96cb3e to your computer and use it in GitHub Desktop.
Use the new `containerBackground` modifier for widgets if iOS 17 is available, or easily fallback to a `ZStack` with standard padding.
//
// WidgetBackground.swift
//
// Created by Kyle Bashour on 6/5/23.
//
import SwiftUI
struct WidgetBackground<Background: View>: ViewModifier {
private let background: Background
init(@ViewBuilder background: () -> Background) {
self.background = background()
}
func body(content: Content) -> some View {
if #available(iOS 17, watchOS 10, *) {
content.containerBackground(for: .widget) {
background
}
} else {
ZStack(alignment: .leading) {
background
content.padding()
}
}
}
}
extension View {
func widgetBackground(@ViewBuilder background: () -> some View) -> some View {
modifier(WidgetBackground(background: background))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment