Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/rshankras/claude-code-apple-skills --skill attributed-string- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads attributed-string automatically when relevant.
- 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
| API | Minimum Version | Notes |
|---|---|---|
AttributedString | iOS 15 / macOS 12 | Swift-native replacement for NSAttributedString |
AttributedString.paragraphStyle | iOS 15 / macOS 12 | Uses NSMutableParagraphStyle |
AttributedString.writingDirection | iOS 26 / macOS 26 | New in 2025 |
AttributedString.LineHeight | iOS 26 / macOS 26 | .exact(points:), .multiple(factor:), .loose |
AttributedString.alignment | iOS 26 / macOS 26 | .left, .center, .right |
AttributedTextSelection | iOS 26 / macOS 26 | Programmatic text selection |
replaceSelection(_:withCharacters:) | iOS 26 / macOS 26 | Replace selection with plain characters |
replaceSelection(_:with:) | iOS 26 / macOS 26 | Replace selection with AttributedString |
DiscontiguousAttributedSubstring | iOS 26 / macOS 26 | Non-contiguous range selections |
AttributedString.utf8 | iOS 26 / macOS 26 | UTF-8 code unit view |
TextEditor(text:selection:) with AttributedString | iOS 26 / macOS 26 | SwiftUI rich text editing |
.textSelectionAffinity(_:) | iOS 26 / macOS 26 | Control cursor affinity at line boundaries |
Top 5 Mistakes
| # | Mistake | Fix |
|---|---|---|
| 1 | Using NSAttributedString in new Swift code | Use AttributedString (iOS 15+) for type-safe, Swift-native attributes |
| 2 | Applying range-based attributes without checking the range exists | Always safely unwrap the result of text.range(of:) before subscripting |
| 3 | Forgetting that AttributedString is a value type | Mutations require var, not let; assign attributes after declaring as var |
| 4 | Building NSMutableParagraphStyle when new alignment API is available | Use text.alignment = .center on iOS 26+ instead of manual paragraph styles |
| 5 | Modifying the original string instead of the selection when using replaceSelection | Pass 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
}
| Pattern | Verdict |
|---|---|
var text = AttributedString("...") then mutate | Correct |
let text = AttributedString("...") then mutate | Will 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:
| Value | Description |
|---|---|
.left | Left-aligned text |
.right | Right-aligned text |
.center | Center-aligned text |
Writing Direction and Line Height
Writing Direction (iOS 26+)
var text = AttributedString("Hello عربي")
text.writingDirection = .rightToLeft
| Value | Description |
|---|---|
.leftToRight | Standard LTR layout |
.rightToLeft | RTL 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
| Mode | Use Case |
|---|---|
.exact(points:) | Pixel-perfect designs with fixed line heights |
.multiple(factor:) | Proportional scaling relative to font size |
.loose | Comfortable 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(notNSAttributedString) for new Swift code - All range lookups safely unwrapped with
if letorguard let - String declared as
varbefore applying attributes -
replaceSelectionpasses selection asinout(&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+) -
.textSelectionAffinityapplied where cursor behavior at line wraps matters -
.textSelection(.enabled)added toTextviews 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
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.
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.
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.
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.
Popular mobile skills
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.
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.
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.
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.
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).
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.
