NSAttributedString は、iOS SDKのFoundationフレームワークのクラスで、個々の文字またはテキスト範囲に適用される書式設定属性のセットを持つ文字列を表します。通常のNSStringとは異なり、NSAttributedStringはUnicode文字だけでなく、文字列の各セグメントの属性(フォント、色、カーニング、配置)の辞書も保存します。Apple Developer Documentation(2026)によると、NSAttributedStringはすべてのiOS UIコンポーネントで書式設定されたテキストを表示するための基盤です。
重要なポイント
NSAttributedString は、書式設定されたテキストを扱うための基本的なiOS/macOSクラスです。文字列に属性(キーと値のペアの辞書。キーはNSAttributedStringKey定数(.font、.foregroundColorなど)、値は対応するオブジェクト(UIFont、UIColor))を追加することでNSStringを拡張します。文字列内の各文字は独自の属性セットを持つことができ、単一の文字列内で混合書式設定を可能にします。
NSAttributedString のアーキテクチャは、属性実行(attribute runs)の概念に基づいています。文字範囲0..5に対して.font属性をUIFont.boldSystemFont(ofSize: 16)に設定すると、その範囲のすべての文字が太字で表示されます。他の文字は異なるフォントを持つか、属性をまったく持たない場合があります。属性付き文字列をレンダリングするとき、UIKitシステムは異なる範囲の特性をマージし、テキストを均一にレンダリングします。
NSAttributedStringは不変です — 作成後、その属性と内容は変更できません。変更のためには、任意の範囲で属性を追加、削除、変更するメソッドを提供するNSMutableAttributedStringサブクラスが存在します。この区別はマルチスレッドにとって重要です。不変のNSAttributedStringはスレッドセーフですが、NSMutableAttributedStringはそうではありません。
NSAttributedString は、NSAttributedStringKeyで定義された約40の標準属性をサポートしています。各属性はテキストの外観の特定の側面(フォント、色、位置、下線、影、カーニング、段落スタイル、ハイパーリンク)に影響します。属性を設定するには、NSAttributedStringKey定数を使用し、対応する型のオブジェクトを割り当てます。
| 属性キー | 値の型 | 目的 |
|---|---|---|
| .font | UIFont | フォントとテキストサイズ |
| .foregroundColor | UIColor | テキストの色 |
| .backgroundColor | UIColor | テキストの背景色 |
| .paragraphStyle | NSParagraphStyle | 配置、行間隔、インデント |
| .kern | NSNumber (Float) | 文字間隔(カーニング) |
| .underlineStyle | NSUnderlineStyle (Int) | 下線スタイル(シングル、ダブル、太字、パターン) |
| .strikethroughStyle | NSUnderlineStyle (Int) | 取り消し線スタイル |
| .link | NSURL | インタラクティブなハイパーリンクのURL |
| .shadow | NSShadow | オフセット、blurRadius、色付きのテキスト影 |
| .baselineOffset | NSNumber (Float) | ベースラインからのテキストオフセット |
NSMutableParagraphStyle は、段落の視覚的特性を管理するオブジェクトです:配置(.alignment: .left、.center、.right、.justified)、行間隔(.lineSpacing)、段落間隔(.paragraphSpacing)、最初の行のインデント(.firstLineHeadIndent)、左右のインデント(.headIndent、.tailIndent)、テキスト方向(.baseWritingDirection)。ParagraphStyleは、段落全体に同じ書式設定が必要な場合に、改行文字を含む範囲に適用されます。
作成 は、文字列と属性の辞書を受け取るイニシャライザを介して行われます。属性は文字列全体に適用されます。混合書式設定(文字列の異なる部分に異なる属性)の場合、特定の範囲に属性を後で追加するNSMutableAttributedStringが使用されます。Objective-C はNSAttributedStringKey: UIFont辞書を使用し、Swiftはタイプセーフな[NSAttributedString.Key: Any]辞書を使用します。
let plainText = "Hello, Swift!"
// Create with uniform attributes for the entire string
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font:
UIFont.systemFont(ofSize: 18),
NSAttributedString.Key.foregroundColor:
UIColor.darkText,
NSAttributedString.Key.kern: 1.5
]
let attributedString =
NSAttributedString(string: plainText,
attributes: attributes)
例は、NSMutableParagraphStyleを介した段落の書式設定を示しています。中央揃え、8ポイントの行間隔、12ポイントの段落間隔が設定されています。ParagraphStyleは.paragraphStyleキーの下で属性辞書に追加されます。NSAttributedString は渡されたparagraphStyleをコピーするため、文字列を作成した後でも、既に作成された文字列に影響を与えずに変更できます。
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
paragraphStyle.lineSpacing = 8.0
paragraphStyle.paragraphSpacing = 12.0
paragraphStyle.firstLineHeadIndent = 20.0
let attributed = NSAttributedString(
string: "Centered paragraph with spacing",
attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
NSMutableAttributedString はNSAttributedStringのサブクラスで、作成後に内容と属性を変更できます。主要なメソッド:範囲に単一の属性を追加するaddAttribute(_:value:range:);複数の属性を追加するaddAttributes(_:range:);範囲内のすべての属性を置き換えるsetAttributes(_:range:);属性を削除するremoveAttribute(_:range:);テキストを置き換えるreplaceCharacters(in:with:)。
addAttribute と addAttributes は、既に設定されている属性を削除せずに既存の属性に追加します。範囲に同じキーの属性が既にある場合、その値が置き換えられます。setAttributes は範囲の属性辞書を完全に置き換えます — 以前に設定されたすべての属性が削除されます。これは単一の文字列を順次書式設定する際に理解することが重要です:addAttributesは既に設定されたフォントや色をリセットしないため、より安全です。
範囲 (NSRange) は NSRange(location: 0, length: 5) 構造体を使用して指定されます。locationは開始インデックス(0ベース)、lengthは文字数です。範囲が文字列の境界を超える場合、NSMutableAttributedStringはNSRangeExceptionをスローします。安全な範囲操作には、NSIntersectionRange や NSUnionRange などのFoundationのNSRangeメソッドを使用します。
let attributed = NSMutableAttributedString(
string: "Bold and red text here")
// Apply bold font to first 9 characters
let boldRange = NSRange(location: 0, length: 9)
attributed.addAttribute(
NSAttributedString.Key.font,
value: UIFont.boldSystemFont(ofSize: 16),
range: boldRange)
// Apply red color to characters 13-16 ("text")
let redRange = NSRange(location: 13, length: 4)
attributed.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.red,
range: redRange)
// Apply underline to the entire string
let fullRange = NSRange(location: 0,
length: attributed.length)
attributed.addAttribute(
NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: fullRange)
NSAttributedStringを表示する最も一般的な方法 は、UILabelのattributedTextプロパティに割り当てることです。textプロパティとは異なり、attributedTextはレンダリングに属性を使用し、混合書式設定をサポートします。重要:attributedTextが設定されている場合、UILabelはfont、textColor、textAlignmentプロパティを無視します — すべての視覚的特性はNSAttributedStringの属性から取得されます。
let label = UILabel()
label.numberOfLines = 0
let fullText = NSMutableAttributedString(
string: "Price: $24.99 per month")
// Format "Price:" label with bold font
let priceLabelRange = NSRange(
location: 0, length: 6)
fullText.addAttribute(
NSAttributedString.Key.font,
value: UIFont.boldSystemFont(ofSize: 16),
range: priceLabelRange)
// Format "$24.99" with green color
let amountRange = NSRange(
location: 7, length: 6)
fullText.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.systemGreen(),
range: amountRange)
fullText.addAttribute(
NSAttributedString.Key.font,
value: UIFont.boldSystemFont(ofSize: 22),
range: amountRange)
// Apply gray color to "per month" text
let periodRange = NSRange(
location: 14, length: 9)
fullText.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.secondaryLabel,
range: periodRange)
label.attributedText = fullText
UITextView はNSAttributedString内のインタラクティブなリンクをサポートしています。NSURLを持つ.link属性はテキストをクリック可能にします。タップを処理するには、textView(_:shouldInteractWith:in:interaction:)メソッドを持つUITextViewDelegateを使用します。UITextViewはテキスト選択や、標準操作(コピー、検索)のためのUIMenuControllerの使用もサポートしています。
NSAttributedString はNSAttributedString.DocumentTypeを介したHTMLおよびRTFからの変換をサポートしています。HTMLをロードするには、documentAttributesパラメータ付きのイニシャライザを使用します:NSAttributedString(data: htmlData, options: [.documentType: .html], documentAttributes: nil)。同様にRTFの場合:.rtf または .rtfd。このメカニズムはWebViewなしでHTMLコンテンツを表示するのに便利です。
HTMLへのエクスポート には、範囲とドキュメントタイプを指定してdata(from:documentAttributes:)メソッドを使用します。HTMLエクスポート:try attributedString.data(from: fullRange, documentAttributes: [.documentType: .html])。結果のデータはファイルに保存したり、サーバーに送信したり、WebViewで表示したりできます。エクスポート中、フォント、色、配置、リスト — すべての書式設定属性 — がCSSスタイルに変換されます。
RTF サポートは、RTFが標準のリッチテキスト形式であるmacOSアプリケーションに特に関連します。iOSもRTFの読み取りと書き込みをサポートしていますが、主要な形式としては使用しません。RTFとRTFDの違い:RTFDにはディレクトリにパッケージ化された埋め込みリソース(画像)が含まれます。NSAttributedString は単一のインターフェースを通じて両方の形式を処理できます。
let htmlString = "<p><b>Bold<\/b> and <i>italic<\/i><\/p>"
guard let htmlData = htmlString.data(
using: String.Encoding.utf8) else { return }
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html
]
let attributedFromHTML =
try? NSAttributedString(
data: htmlData,
options: options,
documentAttributes: nil)
よくある質問
NSString は書式設定情報なしでUnicode文字のシーケンスのみを保存します。NSAttributedString は文字を保存し、各サブ範囲に属性(フォント、色、スタイル)の辞書を含みます。表示時にUIKitはこれらの属性をレンダリングに使用し、書式設定されたテキストを作成します。
最も一般的な理由は、attributedText の代わりに text プロパティを使用することです。textを介して割り当てると、すべての属性が無視されます。2番目の理由:attributedTextを設定した後、UILabelのfont、textColor、またはtextAlignmentを変更すると — これらの変更がattributedTextをリセットします。書式設定されたテキストにはattributedTextのみを使用してください。
NSMutableAttributedString を作成し、異なるフォントの各セグメントに対して addAttribute(.font, value: boldFont, range: boldRange) を呼び出します。各呼び出しは指定された範囲にのみ属性を適用します。残りの文字は標準フォントまたは以前に設定された別のフォントを保持します。これにより、異なるフォントの属性実行が作成されます。
はい、NSAttributedStringは改行文字( )を含む複数行のテキストを正しく処理します。UITextViewとUILabel(numberOfLines = 0)は自動的にテキストを新しい行に折り返します。NSMutableParagraphStyleは各段落の行間隔、インデント、配置を独立して管理します。
各色範囲に対して.foregroundColor属性を持つNSMutableAttributedString を使用します。赤いテキストの場合:addAttribute(.foregroundColor, value: UIColor.red, range: firstRange)。青の場合:addAttribute(.foregroundColor, value: UIColor.blue, range: secondRange)。色は指定された文字範囲にのみ適用されます。
まとめ
ターンキー方式のモバイルアプリケーションを開発します
IT Sectrは2017年からスタートアップや企業向けにiOS・Androidアプリケーションを開発しています。私たちがご相談に乗り、最適なソリューションをご提案します。