Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

widgetkitwidgetkit 控制

Agent Skill

widgetkit 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

29,376

周安装

1,174

GitHub Stars

505

下载量

9,408
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:widgetkit(widgetkit 控制)
来源仓库:https://github.com/dpearson2699/swift-ios-skills
仓库路径:skills/widgetkit
安装命令:
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill widgetkit
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill widgetkit

简介

为 iOS 18+ 构建主屏幕、锁定屏幕、实时活动、动态岛、控制中心和待机小部件。

  • 通过 TimelineProvider 支持静态和可配置的小部件
  • 和 AppIntentTimelineProvider,具有跨系统系列(小型、中型、大型)和配件系列(圆形、矩形、内联)的自适应布局
  • 交互式小部件使用 AppIntent
  • 带按钮
  • 和切换
  • 对于直接行动;动态岛中的实时活动显示具有紧凑、最小和扩展区域
  • 控制中心控件 (iOS 18+) 使用 ControlWidgetButton
  • 和 ControlWidgetToggle
  • ;锁屏小部件以鲜艳或强调模式呈现
  • 需要应用程序组共享数据的权限,NSSupportsLiveActivities = YES
  • 用于实时活动,以及通过 WidgetPushHandler 基于推送的时间线重新加载
  • (iOS 26+)
  • iOS 26 中添加了 Liquid Glass 渲染模式和 CarPlay 小部件支持

SKILL.md

WidgetKit and ActivityKit

Build home screen widgets, Lock Screen widgets, Live Activities, Dynamic Island presentations, Control Center controls, and StandBy surfaces for iOS 26+.

See references/widgetkit-advanced.md for timeline strategies, push-based updates, Xcode setup, and advanced patterns.

Contents

Workflow

1. Create a new widget

  1. Add a Widget Extension target in Xcode (File > New > Target > Widget Extension).
  2. Enable App Groups for shared data between the app and widget extension.
  3. Define a TimelineEntry struct with a date property and display data.
  4. Implement a TimelineProvider (static) or AppIntentTimelineProvider (configurable).
  5. Build the widget view using SwiftUI, adapting layout per WidgetFamily.
  6. Declare the Widget conforming struct with a configuration and supported families.
  7. Register all widgets in a WidgetBundle annotated with @main.

2. Add a Live Activity

  1. Define an ActivityAttributes struct with a nested ContentState.
  2. Add NSSupportsLiveActivities = YES to the app's Info.plist.
  3. Create an ActivityConfiguration in the widget bundle with Lock Screen content and Dynamic Island closures.
  4. Start the activity with Activity.request(attributes:content:pushType:).
  5. Update with activity.update(_:) and end with activity.end(_:dismissalPolicy:).

3. Add a Control Center control

  1. Define an AppIntent for the action.
  2. Create a ControlWidgetButton or ControlWidgetToggle in the widget bundle.
  3. Use StaticControlConfiguration or AppIntentControlConfiguration.

4. Review existing widget code

Run through the Review Checklist at the end of this document.

Widget Protocol and WidgetBundle

Widget

Every widget conforms to the Widget protocol and returns a WidgetConfiguration from its body.

struct OrderStatusWidget: Widget {
    let kind: String = "OrderStatusWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: OrderProvider()) { entry in
            OrderWidgetView(entry: entry)
        }
        .configurationDisplayName("Order Status")
        .description("Track your current order.")
        .supportedFamilies([.systemSmall, .systemMedium])
    }
}

WidgetBundle

Use WidgetBundle to expose multiple widgets from a single extension.

@main
struct MyAppWidgets: WidgetBundle {
    var body: some Widget {
        OrderStatusWidget()
        FavoritesWidget()
        DeliveryActivityWidget()   // Live Activity
        QuickActionControl()       // Control Center
    }
}

Configuration Types

Use StaticConfiguration for non-configurable widgets. Use AppIntentConfiguration (recommended) for configurable widgets paired with AppIntentTimelineProvider.

// Static
StaticConfiguration(kind: "MyWidget", provider: MyProvider()) { entry in
    MyWidgetView(entry: entry)
}
// Configurable
AppIntentConfiguration(kind: "ConfigWidget", intent: SelectCategoryIntent.self,
                       provider: CategoryProvider()) { entry in
    CategoryWidgetView(entry: entry)
}

Shared Modifiers

ModifierPurpose
.configurationDisplayName(_:)Name shown in the widget gallery
.description(_:)Description shown in the widget gallery
.supportedFamilies(_:)Array of WidgetFamily values
.supplementalActivityFamilies(_:)Live Activity sizes (.small, .medium)

TimelineProvider

For static (non-configurable) widgets. Uses completion handlers. Three required methods:

struct WeatherProvider: TimelineProvider {
    typealias Entry = WeatherEntry

    func placeholder(in context: Context) -> WeatherEntry {
        WeatherEntry(date: .now, temperature: 72, condition: "Sunny")
    }

    func getSnapshot(in context: Context, completion: @escaping (WeatherEntry) -> Void) {
        let entry = context.isPreview
            ? placeholder(in: context)
            : WeatherEntry(date: .now, temperature: currentTemp, condition: currentCondition)
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<WeatherEntry>) -> Void) {
        Task {
            let weather = await WeatherService.shared.fetch()
            let entry = WeatherEntry(date: .now, temperature: weather.temp, condition: weather.condition)
            let nextUpdate = Calendar.current.date(byAdding: .hour, value: 1, to: .now)!
            completion(Timeline(entries: [entry], policy: .after(nextUpdate)))
        }
    }
}

AppIntentTimelineProvider

For configurable widgets. Uses async/await natively. Receives user intent configuration.

struct CategoryProvider: AppIntentTimelineProvider {
    typealias Entry = CategoryEntry
    typealias Intent = SelectCategoryIntent

    func placeholder(in context: Context) -> CategoryEntry {
        CategoryEntry(date: .now, categoryName: "Sample", items: [])
    }

    func snapshot(for config: SelectCategoryIntent, in context: Context) async -> CategoryEntry {
        let items = await DataStore.shared.items(for: config.category)
        return CategoryEntry(date: .now, categoryName: config.category.name, items: items)
    }

    func timeline(for config: SelectCategoryIntent, in context: Context) async -> Timeline<CategoryEntry> {
        let items = await DataStore.shared.items(for: config.category)
        let entry = CategoryEntry(date: .now, categoryName: config.category.name, items: items)
        return Timeline(entries: [entry], policy: .atEnd)
    }
}

Widget Families

FamilyPlatform
.systemSmalliOS, iPadOS, macOS, CarPlay (iOS 26+)
.systemMediumiOS, iPadOS, macOS
.systemLargeiOS, iPadOS, macOS
.systemExtraLargeiPadOS only
.accessoryCirculariOS, watchOS
.accessoryRectangulariOS, watchOS
.accessoryInlineiOS, watchOS
.accessoryCornerwatchOS only

Adapt layout per family using @Environment(\.widgetFamily):

@Environment(\.widgetFamily) var family

var body: some View {
    switch family {
    case .systemSmall: CompactView(entry: entry)
    case .systemMedium: DetailedView(entry: entry)
    case .accessoryCircular: CircularView(entry: entry)
    default: FullView(entry: entry)
    }
}

Interactive Widgets (iOS 17+)

Use Button and Toggle with AppIntent conforming types to perform actions directly from a widget without launching the app.

struct ToggleFavoriteIntent: AppIntent {
    static var title: LocalizedStringResource = "Toggle Favorite"
    @Parameter(title: "Item ID") var itemID: String

    func perform() async throws -> some IntentResult {
        await DataStore.shared.toggleFavorite(itemID)
        return .result()
    }
}

struct InteractiveWidgetView: View {
    let entry: FavoriteEntry
    var body: some View {
        HStack {
            Text(entry.itemName)
            Spacer()
            Button(intent: ToggleFavoriteIntent(itemID: entry.itemID)) {
                Image(systemName: entry.isFavorite ? "star.fill" : "star")
            }
        }
        .padding()
    }
}

Live Activities and Dynamic Island

ActivityAttributes

Define the static and dynamic data model.

struct DeliveryAttributes: ActivityAttributes {
    struct ContentState: Codable, Hashable {
        var driverName: String
        var estimatedDeliveryTime: ClosedRange<Date>
        var currentStep: DeliveryStep
    }

    var orderNumber: Int
    var restaurantName: String
}

ActivityConfiguration

Provide Lock Screen content and Dynamic Island closures in the widget bundle.

struct DeliveryActivityWidget: Widget {
    var body: some WidgetConfiguration {
        ActivityConfiguration(for: DeliveryAttributes.self) { context in
            VStack(alignment: .leading) {
                Text(context.attributes.restaurantName).font(.headline)
                HStack {
                    Text("Driver: \(context.state.driverName)")
                    Spacer()
                    Text(timerInterval: context.state.estimatedDeliveryTime, countsDown: true)
                }
            }
            .padding()
        } dynamicIsland: { context in
            DynamicIsland {
                DynamicIslandExpandedRegion(.leading) {
                    Image(systemName: "box.truck.fill").font(.title2)
                }
                DynamicIslandExpandedRegion(.trailing) {
                    Text(timerInterval: context.state.estimatedDeliveryTime, countsDown: true)
                        .font(.caption)
                }
                DynamicIslandExpandedRegion(.center) {
                    Text(context.attributes.restaurantName).font(.headline)
                }
                DynamicIslandExpandedRegion(.bottom) {
                    HStack {
                        ForEach(DeliveryStep.allCases, id: \.self) { step in
                            Image(systemName: step.icon)
                                .foregroundStyle(step <= context.state.currentStep ? .primary : .tertiary)
                        }
                    }
                }
            } compactLeading: {
                Image(systemName: "box.truck.fill")
            } compactTrailing: {
                Text(timerInterval: context.state.estimatedDeliveryTime, countsDown: true)
                    .frame(width: 40).monospacedDigit()
            } minimal: {
                Image(systemName: "box.truck.fill")
            }
        }
    }
}

Dynamic Island Regions

RegionPosition
.leadingLeft of the TrueDepth camera; wraps below
.trailingRight of the TrueDepth camera; wraps below
.centerDirectly below the camera
.bottomBelow all other regions

Starting, Updating, and Ending

let attributes = DeliveryAttributes(orderNumber: 123, restaurantName: "Pizza Place")
let state = DeliveryAttributes.ContentState(
    driverName: "Alex",
    estimatedDeliveryTime: Date()...Date().addingTimeInterval(1800),
    currentStep: .preparing
)
let content = ActivityContent(state: state, staleDate: nil, relevanceScore: 75)
let activity = try Activity.request(attributes: attributes, content: content, pushType: .token)

let updated = ActivityContent(state: newState, staleDate: nil, relevanceScore: 90)
await activity.update(updated)

let final = ActivityContent(state: finalState, staleDate: nil, relevanceScore: 0)
await activity.end(final, dismissalPolicy: .after(.now.addingTimeInterval(3600)))

Control Center Widgets (iOS 18+)

// Button control
struct OpenCameraControl: ControlWidget {
    var body: some ControlWidgetConfiguration {
        StaticControlConfiguration(kind: "OpenCamera") {
            ControlWidgetButton(action: OpenCameraIntent()) {
                Label("Camera", systemImage: "camera.fill")
            }
        }
        .displayName("Open Camera")
    }
}

// Toggle control with value provider
struct FlashlightControl: ControlWidget {
    var body: some ControlWidgetConfiguration {
        StaticControlConfiguration(kind: "Flashlight", provider: FlashlightValueProvider()) { value in
            ControlWidgetToggle(isOn: value, action: ToggleFlashlightIntent()) {
                Label("Flashlight", systemImage: value ? "flashlight.on.fill" : "flashlight.off.fill")
            }
        }
        .displayName("Flashlight")
    }
}

Lock Screen Widgets

Use accessory families and AccessoryWidgetBackground.

struct StepsWidget: Widget {
    let kind = "StepsWidget"
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: StepsProvider()) { entry in
            ZStack {
                AccessoryWidgetBackground()
                VStack {
                    Image(systemName: "figure.walk")
                    Text("\(entry.stepCount)").font(.headline)
                }
            }
        }
        .supportedFamilies([.accessoryCircular, .accessoryRectangular, .accessoryInline])
    }
}

StandBy Mode

.systemSmall widgets automatically appear in StandBy (iPhone on charger in landscape). Use @Environment(\.widgetLocation) for conditional rendering:

@Environment(\.widgetLocation) var location
// location == .standBy, .homeScreen, .lockScreen, .carPlay, etc.

Design Patterns

  • Prefer Gauge over manual arcs. Use .gaugeStyle(.accessoryCircular) for Lock Screen circular widgets and .linearCapacity for home screen capacity bars. The system handles styling, accessibility, and rendering-mode adaptation.
  • Use .containerBackground(_:for:.widget) (iOS 17+) for widget backgrounds instead of padding and background modifiers.
  • Use Canvas for dense visualizations like sparklines or mini bar charts. The lack of per-element accessibility is acceptable since the entire widget surface is a single tap target.
  • Match timeline refresh to data granularity. Apple budgets 40–70 refreshes per day with entries at least 5 minutes apart. Use Text(timerInterval:countsDown:) for live countdowns instead of burning timeline entries.

See references/widgetkit-advanced.md for code examples and detailed guidance on each pattern.

iOS 26 Additions

Liquid Glass Support

Adapt widgets to the Liquid Glass visual style using WidgetAccentedRenderingMode.

ModeDescription
.accentedAccented rendering for Liquid Glass
.accentedDesaturatedAccented with desaturation
.desaturatedFully desaturated
.fullColorFull-color rendering

WidgetPushHandler

Enable push-based timeline reloads without scheduled polling.

struct MyWidgetPushHandler: WidgetPushHandler {
    func pushTokenDidChange(_ pushInfo: WidgetPushInfo, widgets: [WidgetInfo]) {
        let tokenString = pushInfo.token.map { String(format: "%02x", $0) }.joined()
        // Send tokenString to your server
    }
}

CarPlay Widgets

.systemSmall widgets render in CarPlay on iOS 26+. Ensure small widget layouts are legible at a glance for driver safety.

Common Mistakes

  1. Using IntentTimelineProvider instead of AppIntentTimelineProvider. IntentTimelineProvider is the older SiriKit Intents-based provider. Prefer AppIntentTimelineProvider with the App Intents framework for new widgets.
  2. Exceeding the refresh budget. Widgets have a daily refresh limit. Do not call WidgetCenter.shared.reloadTimelines(ofKind:) on every minor data change. Batch updates and use appropriate TimelineReloadPolicy values.
  3. Forgetting App Groups for shared data. The widget extension runs in a separate process. Use UserDefaults(suiteName:) or a shared App Group container for data the widget reads.
  4. Performing network calls in placeholder(). placeholder(in:) must return synchronously with sample data. Use getTimeline or timeline(for:in:) for async work.
  5. Missing NSSupportsLiveActivities Info.plist key. Live Activities will not start without NSSupportsLiveActivities = YES in the host app's Info.plist.
  6. Using the deprecated contentState API. Use ActivityContent for all Activity.request, update, and end calls. The contentState-based methods are deprecated.
  7. Not handling the stale state. Check context.isStale in Live Activity views and show a fallback (e.g., "Updating...") when content is outdated.
  8. Putting heavy logic in the widget view. Widget views are rendered in a size-limited process. Pre-compute data in the timeline provider and pass display-ready values through the entry.
  9. Ignoring accessory rendering modes. Lock Screen widgets render in .vibrant or .accented mode, not .fullColor. Test with @Environment(\.widgetRenderingMode) and avoid relying on color alone.
  10. Not testing on device. Dynamic Island and StandBy behavior differ significantly from Simulator. Always verify on physical hardware.

Review Checklist

  • Widget extension target has App Groups entitlement matching the main app
  • @main is on the WidgetBundle, not on individual widgets
  • placeholder(in:) returns synchronously; getSnapshot/snapshot(for:in:) fast when isPreview
  • Timeline reload policy matches update frequency; reloadTimelines(ofKind:) only on data change
  • Layout adapts per WidgetFamily; accessory widgets tested in .vibrant mode
  • Interactive widgets use AppIntent with Button/Toggle only
  • Live Activity: NSSupportsLiveActivities = YES; ActivityContent used; Dynamic Island closures implemented
  • activity.end(_:dismissalPolicy:) called; controls use StaticControlConfiguration/AppIntentControlConfiguration
  • Timeline entries and Intent types are Sendable; tested on device

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.84%
按下载量换算3,654

Claude

28.57%
按下载量换算2,688

Cursor

20.14%
按下载量换算1,895

Gemini CLI

9.09%
按下载量换算855

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills