MCPInstall

attributed-string

AttributedString patterns for rich text formatting, alignment, selection, and SwiftUI integration. Use when working with styled text, text editing, or AttributedString APIs.

Installs
77
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/rshankras/claude-code-apple-skills --skill attributed-string
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads attributed-string automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

AttributedString Patterns

Correct API shapes and patterns for Foundation's AttributedString. Covers creating styled text, applying attributes to ranges, text alignment, writing direction, line height control, text selection and editing, discontiguous substrings, and SwiftUI integration.

When This Skill Activates

Use this skill when the user:

  • Asks about AttributedString creation or manipulation
  • Wants to style text with fonts, colors, underlines, or other attributes
  • Mentions text alignment, writing direction, or line height
  • Asks about text selection or text editing with AttributedString
  • Wants to work with DiscontiguousAttributedSubstring or RangeSet
  • Mentions TextEditor with AttributedString in SwiftUI
  • Asks about rich text formatting in Swift
  • Wants to replace or modify text within an AttributedString
  • Mentions paragraphStyle, textSelectionAffinity, or AttributedTextSelection

Decision Tree

What do you need with AttributedString?
|
+-- Create or style text
|   |
|   +-- Simple inline attributes (font, color)
|   |   --> Creating and Styling section
|   |
|   +-- Paragraph-level formatting (alignment, line height)
|       --> Text Alignment and Formatting section
|
+-- Control text layout
|   |
|   +-- Writing direction (LTR / RTL)
|   |   --> Writing Direction and Line Height section
|   |
|   +-- Line spacing / height
|       --> Writing Direction and Line Height section
|
+-- Edit or select text programmatically
|   |
|   +-- Replace selection with characters or AttributedString
|   |   --> Text Selection and Editing section
|   |
|   +-- Work with multiple non-contiguous ranges
|       --> DiscontiguousAttributedSubstring section
|
+-- Display in SwiftUI
    --> SwiftUI Integration section

API Availability

APIMinimum VersionNotes
AttributedStringiOS 15 / macOS 12Swift-native replacement for NSAttributedString
AttributedString.paragraphStyleiOS 15 / macOS 12Uses NSMutableParagraphStyle
AttributedString.writingDirectioniOS 26 / macOS 26New in 2025
AttributedString.LineHeightiOS 26 / macOS 26.exact(points:), .multiple(factor:), .loose
AttributedString.alignmentiOS 26 / macOS 26.left, .center, .right
AttributedTextSelectioniOS 26 / macOS 26Programmatic text selection
replaceSelection(_:withCharacters:)iOS 26 / macOS 26Replace selection with plain characters
replaceSelection(_:with:)iOS 26 / macOS 26Replace selection with AttributedString
DiscontiguousAttributedSubstringiOS 26 / macOS 26Non-contiguous range selections
AttributedString.utf8iOS 26 / macOS 26UTF-8 code unit view
TextEditor(text:selection:) with AttributedStringiOS 26 / macOS 26SwiftUI rich text editing
.textSelectionAffinity(_:)iOS 26 / macOS 26Control cursor affinity at line boundaries

Top 5 Mistakes

#MistakeFix
1Using NSAttributedString in new Swift codeUse AttributedString (iOS 15+) for type-safe, Swift-native attributes
2Applying range-based attributes without checking the range existsAlways safely unwrap the result of text.range(of:) before subscripting
3Forgetting that AttributedString is a value typeMutations require var, not let; assign attributes after declaring as var
4Building NSMutableParagraphStyle when new alignment API is availableUse text.alignment = .center on iOS 26+ instead of manual paragraph styles
5Modifying the original string instead of the selection when using replaceSelectionPass the selection as inout and let the API update the selection range for you

Creating and Styling

Basic Initialization

// Plain text
let plain = AttributedString("Hello, world!")

// With attributes applied inline
var bold = AttributedString("Bold text")
bold.font = .boldSystemFont(ofSize: 16)

Applying Attributes to Ranges

var text = AttributedString("Styled text")
text.foregroundColor = .red
text.backgroundColor = .yellow
text.font = .systemFont(ofSize: 14)

// Attribute on a specific range
if let range = text.range(of: "Styled") {
    text[range].underlineStyle = .single
    text[range].underlineColor = .blue
}

Creating from a Substring

let source = AttributedString("Hello, world!")
if let range = source.range(of: "world") {
    let substring = source[range]
    let extracted = AttributedString(substring) // standalone copy
}
PatternVerdict
var text = AttributedString("...") then mutateCorrect
let text = AttributedString("...") then mutateWill not compile -- value type requires var
Force-unwrapping text.range(of:)!Fragile -- use if let or guard let

Text Alignment and Formatting

Legacy Approach (iOS 15+)

var paragraph = AttributedString("Centered paragraph of text")
let style = NSMutableParagraphStyle()
style.alignment = .center
paragraph.paragraphStyle = style

Modern Approach (iOS 26+)

var paragraph = AttributedString("Centered paragraph of text")
paragraph.alignment = .center

Available TextAlignment values:

ValueDescription
.leftLeft-aligned text
.rightRight-aligned text
.centerCenter-aligned text

Writing Direction and Line Height

Writing Direction (iOS 26+)

var text = AttributedString("Hello عربي")
text.writingDirection = .rightToLeft
ValueDescription
.leftToRightStandard LTR layout
.rightToLeftRTL layout for Arabic, Hebrew, etc.

Line Height (iOS 26+)

var multiline = AttributedString(
    "This is a paragraph\nwith multiple lines\nof text."
)

// Exact point value
multiline.lineHeight = .exact(points: 32)

// Multiplier of the default line height
multiline.lineHeight = .multiple(factor: 2.5)

// System-defined loose spacing
multiline.lineHeight = .loose
ModeUse Case
.exact(points:)Pixel-perfect designs with fixed line heights
.multiple(factor:)Proportional scaling relative to font size
.looseComfortable reading spacing chosen by the system

Text Selection and Editing

Replacing Selected Text (iOS 26+)

var text = AttributedString("Here is my dog")
var selection = AttributedTextSelection(range: text.range(of: "dog")!)

// Replace with plain characters
text.replaceSelection(&selection, withCharacters: "cat")

// Replace with an AttributedString
let replacement = AttributedString("horse")
text.replaceSelection(&selection, with: replacement)

Key point: use withCharacters: for plain text, with: for styled replacements.

DiscontiguousAttributedSubstring

Select and manipulate multiple non-contiguous ranges at once (iOS 26+).

let text = AttributedString("Select multiple parts of this text")

if let range1 = text.range(of: "Select"),
   let range2 = text.range(of: "text") {
    let rangeSet = RangeSet([range1, range2])
    var substring = text[rangeSet] // DiscontiguousAttributedSubstring
    substring.backgroundColor = .yellow

    // Flatten into a single contiguous AttributedString
    let combined = AttributedString(substring)
}

UTF-8 View

Access raw UTF-8 code units (iOS 26+):

let text = AttributedString("Hello")
for codeUnit in text.utf8 {
    print(codeUnit)
}

SwiftUI Integration

TextEditor with AttributedString and Selection (iOS 26+)

struct SuggestionTextEditor: View {
    @State var text: AttributedString = ""
    @State var selection = AttributedTextSelection()

    var body: some View {
        VStack {
            TextEditor(text: $text, selection: $selection)
            SuggestionsView(
                substrings: getSubstrings(
                    text: text,
                    indices: selection.indices(in: text)
                )
            )
        }
    }
}

Text Selection Affinity

Control which line the cursor appears on when positioned at a line boundary:

TextEditor(text: $text, selection: $selection)
    .textSelectionAffinity(.upstream)

.upstream keeps the cursor at the end of the previous line; .downstream moves it to the start of the next.

Displaying Styled Text in SwiftUI

// Simple display
Text(attributedString)

// With text selection enabled
Text(attributedString)
    .textSelection(.enabled)

Review Checklist

Correctness

  • Using AttributedString (not NSAttributedString) for new Swift code
  • All range lookups safely unwrapped with if let or guard let
  • String declared as var before applying attributes
  • replaceSelection passes selection as inout (&selection)

Platform and Versioning

  • New APIs (alignment, writingDirection, lineHeight, selection) gated to iOS 26+ / macOS 26+
  • Legacy paragraph style approach used for iOS 15-25 targets
  • Availability checks (if #available) wrap newer APIs when supporting older deployment targets

SwiftUI

  • TextEditor(text:selection:) overload used for rich text editing (iOS 26+)
  • .textSelectionAffinity applied where cursor behavior at line wraps matters
  • .textSelection(.enabled) added to Text views that display user content

Accessibility

  • Foreground and background color combinations meet contrast requirements
  • Styled text does not rely solely on color to convey meaning (add underline, bold, or icons)
  • Writing direction set correctly for RTL language content

References

FAQ

What does the attributed-string skill do?

AttributedString patterns for rich text formatting, alignment, selection, and SwiftUI integration. Use when working with styled text, text editing, or AttributedString APIs.

How do I install attributed-string?

Run npx skills add https://github.com/rshankras/claude-code-apple-skills --skill attributed-string in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/attributed-string/ (personal) or .claude/skills/attributed-string/ (project).

Which AI agents can use attributed-string?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is attributed-string safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains attributed-string?

It is published by rshankras in rshankras/claude-code-apple-skills. It has 77 recorded installs.

More from rshankras/claude-code-apple-skills

View all →

macos-development

rshankras/claude-code-apple-skills

Comprehensive macOS development guidance including Swift 6+, SwiftUI, SwiftData, architecture patterns, AppKit bridging, and macOS 26 Tahoe APIs. Use for macOS code review, best practices, UI review, or platform-specific features.

ios-development

rshankras/claude-code-apple-skills

Comprehensive iOS development guidance including Swift best practices, SwiftUI patterns, UI/UX review against HIG, and app planning. Use for iOS code review, best practices, accessibility audits, or planning new iOS apps.

Mobile823 installs

design

rshankras/claude-code-apple-skills

Design skills for Apple platform UI — Liquid Glass, animations, game feel (haptics, sound, celebrations), UI prototyping, UX writing, SF Symbols, and typography. Use when implementing design language features, adding juice/feedback, writing interface copy, or choosing type and iconography.

Frontend & Design680 installs

app-store

rshankras/claude-code-apple-skills

App Store optimization and marketing skills for descriptions, screenshots, keywords, review responses, and comprehensive promotional strategy. Use when user needs help with App Store presence, ASO, marketing, or customer communication.

Mobile599 installs

watchos

rshankras/claude-code-apple-skills

watchOS development guidance including SwiftUI for Watch, Watch Connectivity, complications, and watch-specific UI patterns. Use for watchOS code review, best practices, or Watch app development.

product-development

rshankras/claude-code-apple-skills

End-to-end product development for iOS/macOS apps. Covers market research, competitive analysis, PRD generation, architecture specs, UX design, implementation guides, testing, and App Store release. Use for product planning, validation, or generating specification documents.

Testing & QA554 installs

Popular mobile skills

View category →

design-mobile-apps

designed-by-ai/skills

Design mobile app screens with Sleek, edit Sleek projects, and implement their designs in React Native or HTML.

Mobile1.1M installs

ios-design

uizze.sh

Design and review iOS UI/UX for iPhone apps in SwiftUI, UIKit, or React Native. Use for mobile app design, screen redesigns, navigation flows, typography, forms, keyboard and safe-area layout, and accessibility checks. Apply Apple Human Interface Guidelines and consult real product references through the optional Uizze connection.

Mobile416.5K installs

vercel-react-native-skills

vercel-labs/agent-skills

React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.

OfficialMobile256.7K installs

animate-expo

emilkowalski/skills

Build animations in React Native and Expo, making the decisions in the order that determines whether they feel right — should it animate, which thread it runs on, which properties, spring or timing, how the gesture hands off, how it degrades. Writes the implementation with Reanimated, Gesture Handler, Expo Router and expo-haptics. Use when animating anything in an Expo app, adding gestures, sheets, screen transitions, press feedback or haptics, or fixing motion that stutters on device. For web animation use animate.

Mobile140.1K installs

xcode-project-setup

firebase/agent-skills

Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).

OfficialMobile131.2K installs

firebase-remote-config-basics

firebase/agent-skills

Manages Firebase Remote Config templates, feature flags, loading strategies, and SDKs (Android, iOS). Use when downloading/deploying remoteconfig JSON templates, managing version history/feature flags, setting in-app defaults, fetchAndActivate(), real-time listeners, or SDK setup. Don't use for Firebase Hosting, Auth, Firestore, Data Connect, Crashlytics, or App Hosting.

OfficialMobile121.7K installs