📌 基本構文
文字列と属性の辞書を使って生成します:
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」が青色に、「楽しく」が下線付きになります。
🎨 主な装飾属性
.font:フォント(太字、斜体、サイズなど).foregroundColor:文字色.backgroundColor:背景色.underlineStyle:下線.strikethroughStyle:打ち消し線.link:タップで開くリンク.kern:文字間隔
📱 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