✨ NSAttributedStringとは?

NSAttributedString は、文字に色・太字・下線・リンクなどの装飾(アトリビュート)を加えるためのクラスです。通常の String よりも表現力が高く、UIの見た目を柔軟にコントロールできます。


…読み込み中…

📌 基本構文

文字列と属性の辞書を使って生成します:

let attributes: [NSAttributedString.Key: Any] = [
  .foregroundColor: UIColor.red,
  .font: UIFont.boldSystemFont(ofSize: 20)
]

let attrString = NSAttributedString(string: "赤くて太字のテキスト", attributes: attributes)

✍️ 書き換え可能な文字列:NSMutableAttributedString

文字列の一部に別々の装飾をつけるには NSMutableAttributedString を使います。 - 詳細

let mutable = NSMutableAttributedString(string: "Swiftで楽しく学ぼう")

mutable.addAttribute(.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: 5))
mutable.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 6, length: 3))

上記の例では、「Swift」が青色に、「楽しく」が下線付きになります。

🎨 主な装飾属性

📱 UILabelで使う

let label = UILabel()
label.attributedText = mutable // NSAttributedString または NSMutableAttributedString を代入

🧪 応用:複数装飾の結合

let hello = NSAttributedString(string: "Hello, ", attributes: [.foregroundColor: UIColor.gray])
let name = NSAttributedString(string: "World!", attributes: [.font: UIFont.boldSystemFont(ofSize: 20)])

let combined = NSMutableAttributedString()
combined.append(hello)
combined.append(name)

label.attributedText = combined

🔗 関連リンク