如何在SwiftUI中使用Assets色集自定义导航栏标题指定字符的颜色
导航栏标题分段着色实现方案
原代码通过UINavigationBar.appearance()全局修改所有导航栏标题颜色的逻辑,无法实现单标题内的分段文本着色,需替换为自定义导航栏TitleView的实现:
- 前置条件:Assets资源中已定义名为
orange1的自定义颜色 - 核心逻辑:桥接UIKit的富文本标签作为导航栏自定义标题,为标题末尾5个字符单独设置颜色
- 全局配置移除:删除原
init方法中所有针对UINavigationBar.appearance()的全局颜色设置,避免无差别影响其他页面的导航栏样式
完整实现代码
import SwiftUI import UIKit // 桥接带富文本的UILabel适配SwiftUI视图体系 struct NavigationTitleLabel: UIViewRepresentable { let attributedTitle: NSAttributedString func makeUIView(context: Context) -> UILabel { let label = UILabel() label.setContentHuggingPriority(.required, for: .horizontal) label.setContentCompressionResistancePriority(.required, for: .horizontal) return label } func updateUIView(_ uiView: UILabel, context: Context) { uiView.attributedText = attributedTitle } } struct MainView: View { // 预构建带分段颜色的导航栏标题富文本 private let customNavTitle: NSAttributedString = { let fullTitle = "HelloWorld" // 基础文本属性匹配系统导航栏默认视觉样式 let baseAttr: [NSAttributedString.Key: Any] = [ .font: UIFont.preferredFont(forTextStyle: .headline), .foregroundColor: UIColor.label ] // 匹配末尾"World"文本的范围 let suffixRange = (fullTitle as NSString).range(of: "World") let mutableAttr = NSMutableAttributedString(string: fullTitle, attributes: baseAttr) // 为目标范围设置Assets中定义的自定义颜色 if suffixRange.location != NSNotFound { mutableAttr.addAttributes([ .foregroundColor: UIColor(named: "orange1") ?? .systemOrange ], range: suffixRange) } return mutableAttr }() var body: some View { NavigationView { Text("Hello, World!") .toolbar { // 将自定义标题视图挂载到导航栏主标题位置 ToolbarItem(placement: .principal) { NavigationTitleLabel(attributedTitle: customNavTitle) } } } } }
实现细节说明
- 富文本加载颜色时加入兜底逻辑,避免Assets资源命名不匹配导致的颜色加载失败
- 基础字体采用系统动态字体,完全对齐原生导航栏标题的视觉效果,避免适配偏移
- 若需适配大标题模式,可调整基础字体为
UIFont.preferredFont(forTextStyle: .largeTitle),结合导航栏滚动状态动态更新文本属性即可
内容的提问来源于stack exchange,提问作者xmetal
相关产品推荐
相关产品推荐

