WatchOS开发:本地通知sashColor设置报错如何解决
WatchKit 本地通知自定义sash颜色报错解决方案
问题核心原因
你遇到的具体报错:
Result of call to 'foregroundColor' is unused
触发报错的根源是两处逻辑错误:
- 对
sashColor的属性定位理解错误:sashColor是WKUserNotificationHostingController提供的可重写属性,属于通知UI层面的配置,不是可以在创建通知请求阶段跨类调用、通过foregroundColor方法修改的对象。你调用的foregroundColor(.blue)是SwiftUI的View修饰符,作用是返回修改颜色后的新View实例,你既没有接收这个返回值,也没有用它修改任何实际生效的配置,编译器自然提示返回值未使用。 - 类内属性定义无效:你在子类里写的
let sashColor = sashColor是无限递归的无效声明,并没有重写系统提供的sashColor属性。
正确实现方式
- 重写通知托管控制器的
sashColor属性
不要自定义同名存储属性,直接重写系统的计算属性返回目标颜色即可:
import SwiftUI import UserNotifications class MyHostingController: WKUserNotificationHostingController<NotificationView> { // 重写系统sashColor属性,直接返回需要的自定义颜色 override var sashColor: Color? { .blue } }
- 移除通知调度逻辑里的无效sashColor代码
sash颜色属于通知UI渲染阶段的配置,不属于UNMutableNotificationContent的可配置项,在添加通知请求的函数中不需要写任何和sashColor相关的代码,系统弹出通知加载你的托管控制器时,会自动读取重写的属性值完成渲染。修正后的通知添加代码如下:
func addNotification() { let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = "Title content" content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) center.add(request) }
注意:所有watchOS通知的自定义UI配置(包括sash颜色、通知界面布局等),都需要在对应的WKUserNotificationHostingController子类中完成,无法在调度本地/远程通知的阶段通过通知内容对象提前设置。
内容的提问来源于stack exchange,提问作者Susan Calvin
相关产品推荐
相关产品推荐

