You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
LeCountdown/LaunchWidget/LaunchWidgetLiveActivity.swift

120 lines
3.4 KiB

//
// LaunchWidgetLiveActivity.swift
// LaunchWidget
//
// Created by Laurent Morvillier on 25/01/2023.
//
import ActivityKit
import WidgetKit
import SwiftUI
struct LaunchWidgetAttributes: ActivityAttributes {
public struct ContentState: Codable, Hashable {
// Dynamic stateful properties about your activity go here!
var ended: Bool
}
// Fixed non-changing properties about your activity go here!
var id: String
var name: String
var endDate: Date
}
struct LiveActivityView: View {
var name: String
var endDate: Date
var body: some View {
HStack {
Text(name)
Spacer()
Text(endDate, style: .timer)
.monospaced()
}.padding()
.font(.title)
}
}
struct LaunchWidgetLiveActivity: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: LaunchWidgetAttributes.self) { context in
// Lock screen/banner UI goes here
HStack {
Text(context.attributes.name)
Spacer()
if !context.state.ended {
Text(context.attributes.endDate, style: .timer)
.monospaced()
} else {
Text("It's time!")
}
}.padding()
.font(.title)
.activityBackgroundTint(Color.cyan)
.activitySystemActionForegroundColor(Color.black)
} dynamicIsland: { context in
DynamicIsland {
// Expanded UI goes here. Compose the expanded UI through
// various regions, like leading/trailing/center/bottom
DynamicIslandExpandedRegion(.leading) {
Text(context.attributes.name)
}
DynamicIslandExpandedRegion(.trailing) {
Text(context.attributes.endDate, style: .timer)
.monospaced()
}
DynamicIslandExpandedRegion(.bottom) {
Button {
self._stop()
} label: {
Text("Stop")
}
}
} compactLeading: {
Text("L")
} compactTrailing: {
Text("T")
} minimal: {
Text("Min")
}
.widgetURL(URL(string: context.attributes.id))
.keylineTint(Color.red)
}
}
fileprivate func _stop() {
}
}
struct LaunchWidgetLiveActivity_Previews: PreviewProvider {
static let attributes = LaunchWidgetAttributes(
id: "",
name: "Tea",
endDate: Date().addingTimeInterval(3600.0))
static let contentState = LaunchWidgetAttributes.ContentState(ended: false)
static var previews: some View {
attributes
.previewContext(contentState, viewKind: .dynamicIsland(.compact))
.previewDisplayName("Island Compact")
attributes
.previewContext(contentState, viewKind: .dynamicIsland(.expanded))
.previewDisplayName("Island Expanded")
attributes
.previewContext(contentState, viewKind: .dynamicIsland(.minimal))
.previewDisplayName("Minimal")
attributes
.previewContext(contentState, viewKind: .content)
.previewDisplayName("Notification")
}
}