iOS Development
Swift Programming
NSAttributedString
Font Customization
Text Styling

Example of NSAttributedString with two different font sizes?

Master System Design with Codemia

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

Introduction

NSAttributedString makes it easy to display mixed font sizes in one label, such as a large number with smaller unit text. The key is combining attributes over ranges in one mutable attributed string. A reusable pattern keeps formatting logic clean and avoids fragile hardcoded indices.

Core Sections

Build a Basic Mixed-font Attributed String

Create one NSMutableAttributedString, then apply font attributes to target ranges.

swift
1import UIKit
2
3let fullText = "42 km"
4let attributed = NSMutableAttributedString(string: fullText)
5
6let numberRange = (fullText as NSString).range(of: "42")
7let unitRange = (fullText as NSString).range(of: "km")
8
9attributed.addAttribute(.font, value: UIFont.systemFont(ofSize: 32, weight: .bold), range: numberRange)
10attributed.addAttribute(.font, value: UIFont.systemFont(ofSize: 16, weight: .regular), range: unitRange)
11
12let label = UILabel()
13label.attributedText = attributed

This is the baseline approach for mixed emphasis text.

Add Color and Baseline Alignment

Different font sizes can misalign visually. Use baseline offset and color attributes for polished results.

swift
attributed.addAttribute(.foregroundColor, value: UIColor.label, range: numberRange)
attributed.addAttribute(.foregroundColor, value: UIColor.secondaryLabel, range: unitRange)
attributed.addAttribute(.baselineOffset, value: 4, range: unitRange)

Small baseline adjustments often improve readability in metric displays.

Build a Reusable Formatter Function

Avoid duplicating attribute code across view controllers. A helper function gives consistent typography.

swift
1func styledDistance(value: Int, unit: String) -> NSAttributedString {
2    let text = "\(value) \(unit)"
3    let result = NSMutableAttributedString(string: text)
4
5    let valueRange = (text as NSString).range(of: "\(value)")
6    let unitRange = (text as NSString).range(of: unit)
7
8    result.addAttributes([
9        .font: UIFont.systemFont(ofSize: 30, weight: .semibold)
10    ], range: valueRange)
11
12    result.addAttributes([
13        .font: UIFont.systemFont(ofSize: 14, weight: .regular),
14        .baselineOffset: 3
15    ], range: unitRange)
16
17    return result
18}

Using helpers makes theme changes significantly easier.

Handle Localization and Dynamic Type

If text is localized, range logic should avoid brittle hardcoded offsets. Compute ranges using string search on localized output. For accessibility, combine attributed styling with scalable fonts.

swift
let big = UIFont.preferredFont(forTextStyle: .title1)
let small = UIFont.preferredFont(forTextStyle: .caption1)

You may still need custom scaling behavior for visually balanced mixed-size text.

Integrate in Reusable Cells

When using attributed strings in table or collection cells, reset label properties during reuse to avoid style carryover. Keep formatting deterministic based on model data.

swift
1override func prepareForReuse() {
2    super.prepareForReuse()
3    titleLabel.attributedText = nil
4}

This prevents stale styling artifacts during fast scrolling.

Apply Attributed Text in SwiftUI via UIKit Bridge

If your project uses SwiftUI but still needs rich attributed formatting, use UIViewRepresentable to host a UILabel. This allows consistent formatting logic across UIKit and SwiftUI screens.

swift
1import SwiftUI
2
3struct AttributedLabelView: UIViewRepresentable {
4    let text: NSAttributedString
5
6    func makeUIView(context: Context) -> UILabel {
7        let label = UILabel()
8        label.numberOfLines = 1
9        return label
10    }
11
12    func updateUIView(_ uiView: UILabel, context: Context) {
13        uiView.attributedText = text
14    }
15}

Keeping one formatter function for both frameworks avoids duplicated typography rules and keeps localization updates centralized.

A centralized text-style factory also reduces visual drift across teams and features.

When visual consistency matters, define typography tokens for value text, unit text, and baseline offset in one theme layer. Then build attributed strings from those tokens rather than hardcoded constants. This makes dark-mode and brand refresh updates straightforward and keeps rendering predictable across different screens.

Add snapshot tests for key attributed labels to prevent subtle typography regressions.

Consistent attributed-text utilities also speed UI maintenance across teams.

It also improves consistency during design-system migrations.

Common Pitfalls

  • Hardcoding numeric ranges that break when text values change.
  • Ignoring baseline adjustment and ending with awkward vertical alignment.
  • Repeating attribute setup code in many view files.
  • Forgetting accessibility scaling for mixed-size text.
  • Not clearing attributed text in reusable UI components.

Summary

  • Use NSMutableAttributedString and range-based attributes for mixed font sizes.
  • Apply font, color, and baseline attributes for polished typography.
  • Encapsulate formatting logic in helper functions.
  • Compute ranges dynamically for localization-safe behavior.
  • Reset attributed content in reusable views to avoid visual artifacts.

Course illustration
Course illustration

All Rights Reserved.