如何让带参数的App Intent将额外参数显示在折叠区域下方?
我正在为iOS 16应用使用App Intents框架添加Intent,其中一个Intent用于打开应用数据库中所有事件的列表视图,应用内该视图有多个筛选器,我尝试在Intent中复现部分筛选功能。
已编写了几个选项:一个展示时间范围(过去/未来/全部事件)的AppEnum,以及一个出版物选择器(每个事件可关联0个或1个出版物)。遵循WWDC2022会话《Dive Into App Intents》中演示的技术,已实现以下代码:
struct OpenEventsList: AppIntent { static var title: LocalizedStringResource = "Open Events List" static var openAppWhenRun: Bool = true @Parameter(title: "Scope") var scope: TimeScope @Parameter(title: "Publication") var publication: PublicationEntity? static var parameterSummary: some ParameterSummary { Summary("Open \(\.$scope) for \(\.$publication)") } @MainActor func perform() async throws -> some IntentResult { // 实现代码省略 } }
这生成了一个可用的快捷指令操作。
在WWDC演讲中,演讲者提到:
你还可以定义哪些参数显示在折叠区域下方,哪些隐藏。这些API功能强大,比如可根据Intent任意参数的实际值,使用When、Otherwise或Switch、Case、Default API来改变摘要内容
但找不到任何解释这些API的资料,苹果文档仅列出了部分相关协议。
我希望将出版物选项移至折叠区域下方,默认参数摘要仅显示时间范围选项,当展开操作框时,才显示出版物选项(以及后续可能添加的其他选项)。
解决方案
1. 将参数移至折叠区域
要把publication参数默认隐藏在折叠的“显示更多”区域,只需修改parameterSummary,用.optional()方法标记该参数为可选附加项:
static var parameterSummary: some ParameterSummary { Summary("Open \(\.$scope)") .optional(\.$publication) }
这样设置后,快捷指令编辑器默认只会显示Scope参数,用户点击操作框的“显示更多”后才会看到Publication选项。如果后续添加其他可选参数,直接继续链式调用.optional(\.$otherParameter)即可。
2. 结合Switch/Case动态调整摘要
如果希望在用户选择了出版物后,摘要自动更新为包含该参数的内容(未选择时只显示时间范围),可以用WWDC提到的Switch/Case/Default API实现动态摘要:
static var parameterSummary: some ParameterSummary { Switch(\.$publication) { Case(nil) { Summary("Open \(\.$scope)") } Default { Summary("Open \(\.$scope) for \(\.$publication)") } } .optional(\.$publication) // 依然保持参数默认在折叠区域 }
这种方式下,当用户未选择出版物时,摘要只显示“Open [时间范围]”;一旦选择了具体出版物,摘要会自动更新为“Open [时间范围] for [出版物名称]”,同时Publication参数始终默认隐藏在折叠区域,需要展开才能编辑。
另外,When/Otherwise API的用法类似,比如针对某个参数的特定值调整摘要:
static var parameterSummary: some ParameterSummary { When(\.$scope, .equalTo(.all)) { Summary("Open all events") .optional(\.$publication) } Otherwise: { Summary("Open \(\.$scope) events") .optional(\.$publication) } }
内容的提问来源于stack exchange,提问作者ScottM

