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

如何修改iOS可操作推送通知中NO按钮的字体颜色?

自定义推送通知操作按钮样式(修改NO按钮字体为红色)

嘿,刚好我之前研究过这个问题!首先得明确一点:系统原生的UNNotificationAction是不支持直接修改按钮字体颜色的——iOS为了保持系统UI的一致性,把这些操作按钮的样式完全接管了,咱们没法直接通过API调整颜色、字体这类属性。

不过别担心,要实现你的需求,咱们可以用**通知内容扩展(UNNotificationContentExtension)**来创建完全自定义的通知界面,这样就能随心所欲控制按钮的样式啦。下面是具体的实现步骤:

步骤1:添加通知内容扩展Target

在Xcode中,点击你的项目文件 → 选择“+”添加新Target → 找到“Notification Content Extension”(在iOS分类下),给它起个名字比如CustomNotificationActionExtension,然后完成创建。

步骤2:设计自定义通知界面

打开扩展里的MainInterface.storyboard,你可以看到一个默认的通知视图。现在咱们把它改成需要的样子:

  • 删除默认的标签,添加两个UIButton,分别设置标题为“YES”和“NO”
  • 把“NO”按钮的字体颜色设置为红色,调整两个按钮的布局(比如横向排列,间距合适)
  • 可以根据需要调整通知视图的背景色、按钮的字体大小等样式

步骤3:处理按钮点击事件

打开扩展的NotificationViewController.swift文件,先在类里添加一个属性来保存当前通知:

var notification: UNNotification?

然后在didReceive(_ notification: UNNotification)方法里保存通知:

override func didReceive(_ notification: UNNotification) {
    self.notification = notification
}

接下来给两个按钮添加点击事件(可以在storyboard里连线,或者用代码添加),处理点击逻辑:

@IBAction func yesButtonTapped(_ sender: UIButton) {
    // 创建响应对象,传递自定义的identifier
    let response = UNNotificationResponse(notification: notification!, identifier: "Yes")
    // 通知主应用处理这个响应
    extensionContext?.notificationResponse = response
    // 关闭通知界面
    extensionContext?.completeRequest(keepAliveCompletionHandler: nil)
}

@IBAction func noButtonTapped(_ sender: UIButton) {
    let response = UNNotificationResponse(notification: notification!, identifier: "no")
    extensionContext?.notificationResponse = response
    extensionContext?.completeRequest(keepAliveCompletionHandler: nil)
}

步骤4:关联通知Category

确保你的主应用注册通知Category时,使用的identifier和扩展里配置的一致:

  1. 在扩展的Info.plist中,找到UNNotificationExtensionCategory字段,设置为你主应用里用的category identifier(比如CustomActionCategory)
  2. 主应用注册category的代码保持原来的逻辑就行:
let yesAction = UNNotificationAction(identifier: "Yes", title: "YES", options: [.foreground])
let noAction = UNNotificationAction(identifier: "no", title: "NO")
let category = UNNotificationCategory(identifier: "CustomActionCategory", actions: [yesAction, noAction], intentIdentifiers: [], options: [])

UNUserNotificationCenter.current().setNotificationCategories([category])

这样当推送到达时,系统会自动使用你自定义的通知界面,而不是默认的操作按钮,你设置的红色字体NO按钮就能正常显示啦!

注意:自定义通知扩展需要适配不同的展示场景(锁屏、横幅、通知中心),记得在storyboard里设置Auto Layout,保证在不同设备和展示模式下布局都正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:53:07