SwiftUI WidgetKit ロック画面用をつくる

公式ドキュメント「Creating Lock Screen Widgets and Watch Complications」
https://developer.apple.com/documentation/widgetkit/creating-lock-screen-widgets-and-watch-complications

画像は「.accessoryCircular」と「.accessoryRectangular」実機実行結果。
あと「.accessoryInline」「.accessoryCorner」がある。
これが出来ればWatchも簡単。以前作成したClockKit版も巻き取らないと。

Example Code

struct PCWidgetAccessory: Widget {
    let kind: String = "Accessory"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
            PCWidgetAccessoryEntryView(entry: entry)
        }
        .configurationDisplayName("Accessory")
        .description("Displays percentages for a given period.")
        .supportedFamilies([.accessoryRectangular, .accessoryCircular])
    }
}

struct PCWidgetAccessoryEntryView : View {
    var entry: Provider.Entry
    
    @Environment(\.widgetFamily) var family
    
    var body: some View {
        switch family {
        case .accessoryInline:
            Text("-")
        case .accessoryRectangular:
            HStack {
                Text(self.entry.pcwidgetmodel.clockDate.toStringStart())
                if self.entry.pcwidgetmodel.clockDate.nowPercent() != -1 {
                    Gauge(value: self.entry.pcwidgetmodel.clockDate.nowPercent() / 100) {
                        Image(systemName: String(self.entry.pcwidgetmodel.selectClock) + ".square")
                    } currentValueLabel: {
                        Text("\(Int(self.entry.pcwidgetmodel.clockDate.nowPercent()))")
                    }
                    .gaugeStyle(.accessoryCircular)
                }
                else {
                    Text("-")
                }
                Text(self.entry.pcwidgetmodel.clockDate.toStringEnd())
            }
        case .accessoryCircular:
            if self.entry.pcwidgetmodel.clockDate.nowPercent() != -1 {
                Gauge(value: self.entry.pcwidgetmodel.clockDate.nowPercent() / 100) {
                    Image(systemName: String(self.entry.pcwidgetmodel.selectClock) + ".square")
                } currentValueLabel: {
                    Text("\(Int(self.entry.pcwidgetmodel.clockDate.nowPercent()))")
                }
                .gaugeStyle(.accessoryCircular)
            }
            else {
                Text("-")
            }
        case .systemSmall:
            Text("-")
        default:
            Text("-")
        }
    }
}

SwiftSwiftUI

Posted by shi-n