如何在Apple CarPlay的CPAlertTemplate中添加图片(附代码)
在Apple CarPlay的CPAlertTemplate中添加图片并显示标题与描述
我需要在Apple CarPlay默认的CPAlertTemplate中添加图片,同时保留警报标题和描述的显示。以下是我当前的实现代码:
func updateCarPlayTemplate(title: String) { guard let interfaceController = carPlayInterfaceController else { return } // Dismiss any existing template interfaceController.dismissTemplate(animated: false) {, in // Define the title and description let title = title // Define the title variants to include the description let titleVariants = [title] // Define the actions let okAction = CPAlertAction(title: "OK", style: .default) { action in // Handle OK action interfaceController.dismissTemplate(animated: true, completion: nil) } // Create and present the alert template let alertTemplate = CPAlertTemplate(titleVariants: titleVariants, actions: [okAction]) interfaceController.presentTemplate(alertTemplate, animated: true) // Dismiss the template automatically after 3 seconds DispatchQueue.main.asyncAfter(deadline: .now() + 3) { interfaceController.dismissTemplate(animated: true, completion: nil) } } }
要实现这个需求,你可以利用CPAlertTemplate的image属性添加图片,同时通过subtitleVariants设置描述文本,还需要修正原代码里的语法错误。修改后的完整代码如下:
func updateCarPlayTemplate(title: String, description: String? = nil, alertImage: UIImage? = nil) { guard let interfaceController = carPlayInterfaceController else { return } // 关闭已存在的模板 interfaceController.dismissTemplate(animated: false) { [weak interfaceController] in guard let interfaceController = interfaceController else { return } // 标题变体数组 let titleVariants = [title] // 描述(副标题)变体数组,有值才传入 let subtitleVariants = description != nil ? [description!] : [] // OK按钮操作 let okAction = CPAlertAction(title: "OK", style: .default) { _ in interfaceController.dismissTemplate(animated: true, completion: nil) } // 初始化带标题、描述和按钮的警报模板 let alertTemplate = CPAlertTemplate(titleVariants: titleVariants, subtitleVariants: subtitleVariants, actions: [okAction]) // 设置警报显示的图片 alertTemplate.image = alertImage // 展示模板 interfaceController.presentTemplate(alertTemplate, animated: true) // 3秒后自动关闭模板 DispatchQueue.main.asyncAfter(deadline: .now() + 3) { interfaceController.dismissTemplate(animated: true, completion: nil) } } }
关键修改说明
- 新增
description和alertImage参数,灵活传入描述文本和图片资源 - 修复原代码中
dismissTemplate闭包的语法错误(移除多余的, in) - 使用
subtitleVariants字段设置警报的描述文本,和titleVariants对应实现标题+描述的显示 - 通过
alertTemplate.image属性绑定要显示的图片,支持传入任意UIImage对象 - 添加
[weak interfaceController]避免循环引用问题
内容的提问来源于stack exchange,提问作者Parveen
相关产品推荐
相关产品推荐

