如何为UNNotificationActionIcon(systemImageName:"circle")设置自定义颜色?
给UNNotificationAction的系统图标设置自定义颜色
iOS 15及以上版本(推荐方案)
利用UNNotificationCategoryAppearance可以直接为分类下的所有通知操作图标统一设置自定义颜色,完全适配用户选色需求,步骤如下:
- 根据用户选择的颜色创建外观配置
let appearance = UNNotificationCategoryAppearance() appearance.actionIconColor = userSelectedColor // userSelectedColor为用户选择的UIColor实例
- 创建包含目标操作的通知分类,绑定上述外观
// 创建带系统图标的操作 let colorAction = UNNotificationAction(identifier: "colorAction", title: "自定义颜色操作", options: [], icon: UNNotificationActionIcon(systemImageName: "circle")) // 创建分类并关联外观 let category = UNNotificationCategory(identifier: "customColorCategory", actions: [colorAction], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "", categorySummaryFormat: "", appearance: appearance)
- 向通知中心注册该分类
UNUserNotificationCenter.current().setNotificationCategories([category])
触发该分类的通知时,操作栏里的圆形图标会自动显示用户选择的颜色。
兼容iOS 14及以下版本的方案
如果需要支持更低版本,可通过动态生成带颜色的模板图片并保存到应用可访问路径,再用UNNotificationActionIcon(templateImageName:)引用:
- 生成带指定颜色的系统图标图片
func generateColoredSystemImage(named systemName: String, color: UIColor) -> UIImage? { guard let baseImage = UIImage(systemName: systemName)?.withRenderingMode(.alwaysTemplate) else { return nil } let renderer = UIGraphicsImageRenderer(size: baseImage.size) return renderer.image { context in color.setFill() baseImage.draw(in: CGRect(origin: .zero, size: baseImage.size)) } }
- 将生成的图片保存到应用临时目录
func saveImageToTemp(_ image: UIImage) -> String? { guard let imageData = image.pngData() else { return nil } let tempDir = NSTemporaryDirectory() let fileName = "customColoredCircle.png" let filePath = tempDir.appending(fileName) do { try imageData.write(to: URL(fileURLWithPath: filePath)) return fileName } catch { print("保存图片失败: \(error)") return nil } }
- 使用保存的图片创建通知操作
if let coloredImage = generateColoredSystemImage(named: "circle", color: userSelectedColor), let imageName = saveImageToTemp(coloredImage) { let colorAction = UNNotificationAction(identifier: "colorAction", title: "自定义颜色操作", options: [], icon: UNNotificationActionIcon(templateImageName: imageName)) // 后续创建分类并注册的步骤同上 }
注意:临时目录文件可能被系统自动清理,建议每次创建通知操作前重新生成并保存图片。
内容的提问来源于stack exchange,提问作者Georgii Maltsev
相关产品推荐
相关产品推荐

