NSAttributedString
string color customization
iOS development
Swift programming
text styling

Change string color with NSAttributedString?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

NSAttributedString lets you style text ranges without splitting labels into multiple views. Changing string color is one of its most common uses: highlight keywords, style mentions, or differentiate status segments in a single line. The key is applying attributes to precise ranges and keeping UIKit/AppKit compatibility in mind.

Most bugs come from incorrect range calculation with Unicode content, overriding attributes accidentally, or mixing plain and attributed text updates.

Core Sections

1. Apply one color to full string

swift
1import UIKit
2
3let text = "Build succeeded"
4let attrs: [NSAttributedString.Key: Any] = [
5    .foregroundColor: UIColor.systemGreen,
6    .font: UIFont.systemFont(ofSize: 16, weight: .medium)
7]
8let attributed = NSAttributedString(string: text, attributes: attrs)
9label.attributedText = attributed

This sets base style for entire label text.

2. Color only a substring

swift
1let text = "Status: Failed"
2let mutable = NSMutableAttributedString(string: text)
3
4if let range = text.range(of: "Failed") {
5    let nsRange = NSRange(range, in: text)
6    mutable.addAttribute(.foregroundColor, value: UIColor.systemRed, range: nsRange)
7}
8
9label.attributedText = mutable

Use Swift Range to NSRange conversion to avoid Unicode index issues.

3. Compose multiple styles safely

You can combine color, font, underline, and paragraph styles on different ranges.

swift
1mutable.addAttributes([
2    .font: UIFont.boldSystemFont(ofSize: 16),
3    .foregroundColor: UIColor.systemBlue
4], range: nsRange)

Prefer addAttributes when applying multiple properties at once.

4. Keep dynamic updates idempotent

If text updates frequently (for example status polling), rebuild attributed text from source each update rather than mutating old state repeatedly.

5. Button titles and text views

For UIButton use setAttributedTitle(_:for:); for UITextView, assign attributedText and ensure text container styling does not override your attributes.

Common Pitfalls

  • Calculating NSRange manually with integer offsets and breaking on Unicode strings.
  • Setting label.text after label.attributedText and unintentionally discarding styling.
  • Reusing mutable attributed strings across UI updates without resetting base attributes.
  • Applying conflicting attributes on overlapping ranges in the wrong order.
  • Forgetting control-state-specific attributed titles on buttons.

Summary

Changing string color with NSAttributedString is straightforward when range handling is correct and updates are structured cleanly. Build a base attributed string, apply targeted attributes to substring ranges, and assign to the appropriate UI element API (attributedText or setAttributedTitle). With Unicode-safe ranges and predictable update flow, rich text styling remains reliable and easy to maintain.

A practical way to keep this issue solved is to convert the guidance into a repeatable runbook that can be executed by anyone on the team. Write down the exact environment assumptions, dependency versions, runtime flags, and validation commands required to confirm the behavior. Include expected outputs for the happy path and one or two known failure signatures so the next engineer can quickly classify what they are seeing. This turns fragile tribal knowledge into an operational artifact that survives handoffs, on-call rotations, and context switches.

It is also useful to add one lightweight automated guardrail in CI so regressions are caught before deployment. The guardrail should target the most failure-prone step in the workflow: an import smoke test, configuration lint, compatibility check, integration probe, or small benchmark assertion. Keep that check fast enough to run on every change and explicit enough that failure messages are actionable. In teams with parallel contributors, early automated detection prevents repeated debugging of the same class of issue.

Finally, keep examples current as tools and frameworks evolve. A command or API that worked six months ago may become deprecated, renamed, or behaviorally different. Treat documentation updates as normal maintenance work, just like test upkeep. When guidance is version-aware and tested regularly, you avoid drift between article recommendations and production reality, and the content remains useful for both new and experienced engineers.


Course illustration
Course illustration

All Rights Reserved.