Structure

AttributedString

A value type for a string with associated attributes for portions of its text. それのテキストのいくつかの部分に関連属性をもつ文字列のための値型。

Declaration 宣言

@dynamicMemberLookup struct AttributedString

Overview 概要

Attributed strings are character strings that have attributes for individual characters or ranges of characters. Attributes provide traits like visual styles for display, accessibility for guided access, and hyperlink data for linking between data sources. Attribute keys provide the name and value type of each attribute. System frameworks like Foundation and SwiftUI define common keys, and you can define your own in custom extensions. 属性キーは、各属性の名前と値の型を提供します。Foundation および SwiftUI のようなシステムフレームワークは、共通のキーを定義します、そしてあなたはあなた独自のものをあつらえの拡張の中で定義できます。

String Attributes

You can apply an attribute to an entire string, or to a range within the string. The string represents each range with consistent attributes as a run.

AttributedString uses subscripts and dynamic member lookup to simplify working with attributes from your call points. In its most verbose form, you set an attribute by creating an AttributeContainer and merging it into an existing attributed string, like this:


var attributedString = AttributedString("This is a string with empty attributes.")
var container = AttributeContainer()
container[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self] = .red
attributedString.mergeAttributes(greenContainer, mergePolicy: .keepNew)

Using the attributed string’s subscript(_:) method, you can omit the explicit use of an AttributeContainer and just set the attribute by its type:


attributedString[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self] = .yellow

Because an AttributedString supports dynamic member lookup — as described under Attributes in The Swift Programming Language — you can access its subscripts with dot syntax instead. When combined with properties like foregroundColor that return the attribute key type, this final form offers a natural way to set an attribute that applies to an entire string:


attributedString.foregroundColor = .green

This example works because AppKit defines an AttributeScope, AttributeScopes.AppKitAttributes, in which the property foregroundColor returns the type AttributeScopes.AppKitAttributes.ForegroundColorAttribute. Because AppKit’s attribute scope implements AttributeDynamicLookup, the dot syntax resolves to an equivalent subscript expression, allowing attributedString.foregroundColor to replace attributedString[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self].

You can also set an attribute to apply only to part of an attributed string, by applying the attribute to a range, as seen here:


var attributedString = AttributedString("The first month of your subscription is free.")
let range = attributedString.range(of: "free")!
attributedString[range].foregroundColor = .green

You can access portions of the string with unique combinations of attributes by iterating over the string’s runs property. あなたは属性の固有の組み合わせをもつ文字列の一部分に、文字列のもつrunsプロパティに対して反復していくことによってアクセスできます。

You can define your own custom attributes by creating types that conform to AttributedStringKey, and collecting them in an AttributeScope. Custom keys should also extend AttributeDynamicLookup, so callers can use dot-syntax to access the attribute.

Creating Attributed Strings with Markdown

You can create an attributed string by passing a standard String or Data instance that contains Markdown to initializers like init(markdown:options:baseURL:). The attributed string creates attributes by parsing the markup in the string.


do {
    let thankYouString = try AttributedString(
        markdown:"**Thank you!** Please visit our [website](https://example.com)")
} catch {
    print("Couldn't parse: \(error)")
}

Localized strings that you load from strings files with initializers like init(localized:options:table:bundle:locale:comment:) can also contain Markdown to add styling. In addition, these localized attributed string initializers can apply the replacementIndex attribute, which allows you to determine the range of replacement strings, whose order may vary between languages.

By declaring new attributes that conform to MarkdownDecodableAttributedStringKey, you can add attributes that you invoke by using Apple’s Markdown extension syntax: ^[text](name:value, name:value, …). See the sample code project Building a Localized Food-Ordering App for an example of creating custom attributes and using them with Markdown.

Localized attributed strings can also use the extension syntax to indicate parts of the string where the system can apply automatic grammar agreement. See the initializers that take a localized: parameter for examples of this extension syntax, as used with automatic grammar agreement.

Attribute Scopes 属性スコープ

The AttributedString API defines keys for common uses, such as text styling, semantically marking up formattable types like dates and numbers, and hyperlinking. AttributedString API は、一般的な利用のためのキーを定義します、たとえばテキストスタイル、日付および数値のような意味論的なマークアップ書式設定可能型、、そしてハイパーリンクなど。 You can find these in the AttributeScopes enumeration, which contains attributes for AppKit, Foundation, SwiftUI, and UIKit.

You can define your own attributes by implementing AttributedStringKey, and reference them by name by collecting them in an AttributeScope. あなたは、あなた独自の属性それらをAttributedStringKeyを実装することによって定義できます、そしてそれらを名前によって参照できます、それらをAttributeScopeの中に収集することによって。

Topics 話題

Creating an Attributed String 属性付き文字列を作成する

Creating an Attributed String from Literal Values ある属性付き文字列をリテラル値それらから作成する

Creating a Localized Attributed String ローカライズされた属性付き文字列を作成する

Creating an Attributed String from a Reference Type 属性付き文字列を参照型から作成する

Creating an Attributed String from Markdown 属性付き文字列をMarkdownから作成する

Use Markdown syntax to initialize an attributed string with text and attributes.

Creating a Duplicate Attributed String

Applying and Modifying Attributes 属性の適用と修正

Using Defined Attributes 定義された属性を使う

Searching for a Substring 下位文字列を検索する

Accessing a Range ある範囲にアクセスする

Accessing Indices インデックスにアクセスする

Accessing Views into the Attributed String 属性付き文字列へのビューそれらにアクセスする

Modifying an Attributed String

Transforming Attributes 属性を変換する

Accessing Whole-String Attributes 文字列属性全体にアクセスする

Combining Attributed Strings 属性付き文字列を結合する

Performing Automatic Grammar Agreement 自動文法一致を実行する

Performing String Interpolation 文字列補間を実行する

Comparing Attributed Strings 属性付文字列を比較する

Hashing ハッシュ化

Encoding and Decoding エンコーディングとデコーディング

Describing an Attributed String

See Also 参照

Strings with Metadata メタデータを持つ文字列