LoginSignup
7

posted at

updated at

iOS16新機能ロック画面ウィジェットの対応方法

起きたらiOS16がリリースされたので、自分のためのロックスクリーンウィジェット作り

iOS16でようやくロック画面にもウィジェットを配置できるようになった

ロック画面用のウィジェット3種類が追加された

WidgetFamilyに .accessoryInline.accessoryCircular.accessoryRectangular の3種類が追加されています。

.accessoryInlineは上の画像では日付が表示されている部分、

.accessoryCircular.accessoryRectangularは時計の下のエリアに配置できるようです。
.accessoryCircularはまるく切りに抜かれて1スロット使用、.accessoryRectangularは2スロット使用され、合計で4スロットまで配置できます。(少ない・・・)

ちなみにこれまでのホーム画面ウィジェットは、大中小で以下のサイズです。
.systemLarge.systemMedium.systemSmall

対応させる

.supportedFamiliesに対応させたいウィジェットの種類を列挙します。
.accessoryRectangular を追加

Widget.swift
@main
struct portsWidget: Widget {
    let kind: String = "portsWidget"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
            portsWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("ports")
        .description("my ports.")
        .supportedFamilies([
            .systemSmall,
            .accessoryRectangular,
        ])
    }
}

SwiftUI側では、widgetFamilyでそれぞれviewを実装します。

portsWidgetEntryView.swift
struct portsWidgetEntryView : View {
    var entry: Provider.Entry

    @Environment(\.widgetFamily) private var widgetFamily

    var body: some View {
        switch widgetFamily {
        case .systemSmall:
            VStack {
                Text(entry.getPortName())
                HStack {
                    Rectangle()
                        .frame(width: 5, height: 20)
                        .foregroundColor(entry.getColor())
                    Text(entry.getCount()).bold()
                }.padding()
                Text(entry.getDate(), style: .time).font(.footnote)
            }
        case .accessoryRectangular:
            VStack {
                Text(entry.getPortName()).font(.footnote)
                Text(entry.getCount()).bold()
                Text(entry.getDate(), style: .time).font(.footnote)
            }
        default:
            EmptyView()
        }
    }
}

これだけでロック画面ウィジェットに対応できました。

ユーザー設定によって色は色を変えられたり、モノクロにできたりするので、実装は面倒そう、
今回は自分用なので色が付いてた部分は削除してしまいました。

おわり

iPhone 14 Proからalways-on displayなのでさらに便利!

今年のWWDCに"Complications and widgets: Reloaded"というセッションがあるので、Lock screen widgetsこちらで詳しく説明されています。
https://developer.apple.com/videos/play/wwdc2022/10050/

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
7