没有公共 API 可以为大标题设置您自己的属性文本。
解决方案是向下导航视图层次结构。您特别提到您想避免这种情况,但这是修改颜色同时免费获得其余 UINavigationBar 行为的唯一方法。
当然,您始终可以创建自己的UILabel 并设置其attributedText,但您必须自己重新创建任何导航栏动画和其他行为。
老实说,最简单的解决方案是修改您的设计,使其不需要多色大标题,因为目前不支持。
我在“探索”的道路上进行了深入探索,但动画突然恢复到原始文本颜色时存在各种视觉问题。
如果它对任何试图达到类似效果的人有用的话,这是我使用的代码:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
applyColorStyle(toLabels: findTitleLabels())
}
private func applyColorStyle(toLabels labels: [UILabel]) {
for titleLabel in labels {
let attributedString = NSMutableAttributedString(string: titleLabel.text ?? "")
let fullRange = NSRange(location: 0, length: attributedString.length)
attributedString.addAttribute(NSAttributedStringKey.font, value: titleLabel.font, range: fullRange)
let colors = [UIColor.red, UIColor.orange, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.purple]
for (index, color) in colors.enumerated() {
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSRange(location: index, length: 1))
}
titleLabel.attributedText = attributedString
}
}
private func findTitleLabels() -> [UILabel] {
guard let navigationController = navigationController else { return [] }
var labels = [UILabel]()
for view in navigationController.navigationBar.subviews {
for subview in view.subviews {
if let label = subview as? UILabel {
if label.text == title { labels.append(label) }
}
}
}
return labels
}
“探索”方法的缺点是它不是受支持的 API,这意味着它很容易在未来的更新中中断,或者在各种边缘情况下无法按预期工作。