Last active
June 6, 2023 00:18
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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