Widgets are self-contained: we can adapt them while also supporting older versions of our macOS/iOS’s.
Use
.previewContent(WidgetPreviewContext(family: .system..))on SwiftUI previews to display the widget layout.Do not define your own corner radius in a widget, use
ContainerRelativeShapeinstead:
struct PillView : View {
var title: Text
var color: Color
var body: some View {
Text(title)
.background(ContainerRelativeShape().fill(color))
}
}ContainerRelativeShapeis a new shape type that will take on the path of the nearest container shape specified by a parent with an appropriate corner radius based on the position of the shape.use the
.isPlaceholder(true)modifier on a preview to display the widget preview (note:.isPlaceholderis not available on Xcode 12b1)if something should not be replaced by a placeholder, we need to mark it with
.isPlaceholder(false)if we want the same view to support multiple widget families/sizes, we can to so by adding an environment variable for the widget family:
@Environment(\.widgetFamily) var widgetFamilyTo display a live countdown or similar, use the new Date API:
// +2 hours
// -3 months
Text(event.startDate, style: .offset)
// 2 hours, 23 minutes – Automatically updating as time pass
Text(event.startDate, style: .relative)
// 36:59:01 – Automatically updating as time pass
Text(event.startDate, style: .timer)These date formats will automatically update the view as time passes (without the need of redrawing it): it’s a great way to make your widgets feel alive on the home screen.
