Логотип Attributed String

Attributed String

Спільнота
rshankras
attributed-string

Шаблони AttributedString для форматування насиченого тексту, вирівнювання, виділення та інтеграції зі SwiftUI. Використовуйте під час роботи зі стилізованим текстом, редагуванням тексту або API AttributedString.

Add to TypingMind

Огляд

Видавецьrshankras
Репозиторійclaude-code-apple-skills
Назва навичкиattributed-string
Зірки
744
Форки
70
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Видавець на GitHub: rshankras. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Attributed String у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/rshankras/claude-code-apple-skills/tree/main/skills/foundation/attributed-string
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/rshankras/claude-code-apple-skills.git /tmp/claude-code-apple-skills
mkdir -p .claude/skills
cp -r /tmp/claude-code-apple-skills/skills/foundation/attributed-string .claude/skills/attributed-string
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Attributed String в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Attributed String, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Attributed String не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

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

swift
// 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

swift
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

swift
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+)

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

Modern Approach (iOS 26+)

swift
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+)

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

Line Height (iOS 26+)

swift
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+)

swift
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+).

swift
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+):

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

SwiftUI Integration

TextEditor with AttributedString and Selection (iOS 26+)

swift
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:

swift
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

swift
// 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

Поширені запитання

Що робить навичка ШІ Attributed String?

Шаблони AttributedString для форматування насиченого тексту, вирівнювання, виділення та інтеграції зі SwiftUI. Використовуйте під час роботи зі стилізованим текстом, редагуванням тексту або API AttributedString.

Навіщо використовувати Attributed String у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Attributed String — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Attributed String у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/rshankras/claude-code-apple-skills/tree/main/skills/foundation/attributed-string. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Attributed String?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Attributed String?

Зі скількома забажаєте. У TypingMind ви можете використовувати Attributed String із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Attributed String?

Так. На GitHub цю навичку публікує rshankras за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇