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

如何在CarPlay中用CPListTemplate创建带Toggle的设置界面?

在CarPlay中用CPListTemplate实现带切换开关的设置项

可以通过给CPListItem配置CPSwitchAccessory来实现每行带切换开关的设置界面,具体实现步骤和代码如下:

  • 创建CPSwitchAccessory实例,绑定开关状态变化的回调逻辑
  • 将开关配件赋值给CPListItem的accessory属性
  • 把配置好的列表项加入分区,再生成CPListTemplate并推入CarPlay界面栈

示例代码(Swift):

// 初始化开关配件,设置初始状态和回调
let notificationSwitch = CPSwitchAccessory(isOn: true) { (accessory, isOn) in
    // 这里处理开关状态变化后的业务逻辑
    print("通知开关状态更新为:\(isOn)")
}

// 创建列表项,设置标题和详情文本
let notificationItem = CPListItem(text: "通知提醒", detailText: "接收新消息通知")
notificationItem.accessory = notificationSwitch

// 创建更多设置项(示例)
let soundSwitch = CPSwitchAccessory(isOn: false) { (accessory, isOn) in
    print("音效开关状态更新为:\(isOn)")
}
let soundItem = CPListItem(text: "音效反馈", detailText: "操作时播放提示音")
soundItem.accessory = soundSwitch

// 组装分区和模板
let settingsSection = CPListSection(items: [notificationItem, soundItem])
let settingsTemplate = CPListTemplate(title: "设置", sections: [settingsSection])

// 将模板推入CarPlay界面栈
if let interfaceController = CPInterfaceController.shared {
    interfaceController.pushTemplate(settingsTemplate, animated: true)
}

如果之前没显示出开关,大概率是没有正确给CPListItem设置accessory属性,或者未将模板正确推入CarPlay的界面控制器栈中。另外要确保你的项目已正确配置CarPlay相关权限(entitlements),并在支持的设备或模拟器上测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:25:44