使用WKUserNotificationHostingController自定义长通知时标题与sashColor不显示
解决Apple Watch自定义长通知的标题显示与Sash颜色问题
问题描述
在构建Apple Watch自定义长通知时,遇到两个不符合预期的问题:
UNMutableNotificationContent中定义的title未在长通知上显示(短通知切换到长通知前可短暂显示标题)- 重写的
sashColor自定义背景色完全未生效
根据苹果《Presenting Notifications on Apple Watch》文档,长通知的sash区域应包含通知标题和自定义背景色,但实际运行效果与文档截图不符。
解决方案
要让标题显示并使sashColor生效,只需对watchOS端的通知控制器做两处关键修改:
核心修改逻辑
自定义长通知不会自动渲染通知标题,必须手动将通知的title绑定到控制器的sashTitle属性;同时只有当sash区域存在标题内容时,自定义的sashColor才会被触发显示。
修改后的TakeActionNotificationController代码如下:
import SwiftUI import UserNotifications class TakeActionNotificationController: WKUserNotificationHostingController<TakeActionNotificationView> { private var receivedNotification: UNNotification? // 自定义sash背景色 override class var sashColor: Color? { return .red } override var body: TakeActionNotificationView { TakeActionNotificationView() } override func didReceive(_ notification: UNNotification) { receivedNotification = notification // 将通知标题赋值给sashTitle,触发sash区域显示 sashTitle = notification.request.content.title } }
额外验证要点
- 确保watchOS应用的部署目标为watchOS 7.0及以上(
sashColor与sashTitle属性从该版本开始支持) - 重新运行应用后,调度通知并锁定iPhone,通知推送到Apple Watch时,长通知的sash区域会显示红色背景与"Take Action!"标题,下方正常展示自定义通知内容。
内容的提问来源于stack exchange,提问作者gohnjanotis
相关产品推荐
相关产品推荐

