You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Widget设置选择中为EntityQuery设置默认项?

实现Widget默认选中多组实体的解决方案

你需要实现类似苹果时钟Widget的效果:添加Widget时默认预设一组时段,进入设置界面也有部分时段默认选中,但当前使用EntityQuery仅显示选择选项,无默认内容。以下是针对性的修改方案:

问题分析

你的代码中MyQuery的defaultResult()仅返回单个实体,而多选场景下,默认选中的配置需要在Widget配置Intent的参数中设置默认值,而非仅依赖EntityQuery的单个默认结果。

修改步骤

1. 配置Widget Intent的默认选中实体

创建或修改你的Widget配置Intent,在实体参数中指定默认选中的ID数组:

@available(iOS 17.0, *)
struct SelectTimeSlotsIntent: WidgetConfigurationIntent {
    static var title: LocalizedStringResource = "选择时段"
    static var description = IntentDescription("选择要显示的时段")
    
    // 设置默认选中的实体ID,对应你MyEntity.all中的id字段
    @Parameter(title: "时段", default: ["123", "111"])
    var timeSlots: [MyEntity]
}

2. 关联Widget配置与Intent

在Widget的配置代码中使用该Intent,并确保Provider能处理默认选中的实体:

@available(iOS 17.0, *)
struct MyWidget: Widget {
    let kind: String = "com.yourdomain.MyWidget"

    var body: some WidgetConfiguration {
        AppIntentConfiguration(kind: kind, intent: SelectTimeSlotsIntent.self, provider: Provider()) { entry in
            MyWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("我的时段Widget")
        .description("展示默认选中的时段")
    }
}

3. 保留现有Entity与Query代码(无需修改核心逻辑)

你的MyEntity和MyQuery代码已经能正确根据ID返回实体,只需确保MyEntity.all中的ID与Intent默认值匹配:

@available(iOSApplicationExtension 17.0, *)
struct MyEntity: AppEntity {
    
    var id: String
    var title: String
    
    static var defaultQuery = MyQuery()
    
    static var typeDisplayRepresentation: TypeDisplayRepresentation = "Action"
    
    var displayRepresentation: DisplayRepresentation {
        DisplayRepresentation(title: "\(self.id)")
    }
    
    static var all: [MyEntity] = [
        MyEntity(id: "123", title: "123"),
        MyEntity(id: "111", title: "111"),
        MyEntity(id: "222", title: "222"),
        MyEntity(id: "333", title: "333")
    ]
}

@available(iOSApplicationExtension 17.0, *)
struct MyQuery: EntityQuery {
    
    func entities(for identifiers: [MyEntity.ID]) async throws -> [MyEntity] {
        MyEntity.all.filter {
            identifiers.contains($0.id)
        }
    }
    
    func suggestedEntities() async throws -> [MyEntity] {
        MyEntity.all
    }
    
    func defaultResult() async -> MyEntity? {
        do {
            return try await self.suggestedEntities().first
        } catch {
            return nil
        }
    }
}

关键说明

  • 多选场景下,EntityQuery的defaultResult()不会被调用,默认选中逻辑由Intent参数的default值控制。
  • 确保Intent中设置的默认ID与MyEntity.all中的id完全一致,否则无法加载对应的默认实体。

内容的提问来源于stack exchange,提问作者Anton Timonin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:47:25