UILabelをNSAttributedStringで文字装飾(Swift 4対応)


NSAttributedString

まずは単純なフォントと色替え。

let stringAttributes: [NSAttributedStringKey : Any] = [
    .foregroundColor : UIColor.blue,
    .font : UIFont.systemFont(ofSize: 24.0)
]
let string = NSAttributedString(string: "BlueString", attributes:stringAttributes)
label.attributedText = string

このようになります。

この程度ならUILabel#font、textColorプロパティを使えば同等のことができるので、NSAttributedStringを使うまでもないでしょう。

NSMutableAttributedString

実際にNSAttributedStringを使う時は、文字の一部の色やフォントを変更したり、異なるフォントや色の文字を混ぜたい時だと思います。この時は、NSMutableAttributedStringを使うと良いでしょう。NSMutableAttributedStringは複数のNSAttributedStringを追加してくことで文字装飾します。

let stringAttributes1: [NSAttributedStringKey : Any] = [
    .foregroundColor : UIColor.blue,
    .font : UIFont.systemFont(ofSize: 24.0)
]
let string1 = NSAttributedString(string: "0123", attributes: stringAttributes1)

let stringAttributes2: [NSAttributedStringKey : Any] = [
    .foregroundColor : UIColor.red,
    .font : UIFont.boldSystemFont(ofSize: 20.0)
]
let string2 = NSAttributedString(string: "456", attributes: stringAttributes2)

let stringAttributes3: [NSAttributedStringKey : Any] = [
    .foregroundColor : UIColor.green,
    .font : UIFont.systemFont(ofSize: 16.0)
]
let string3 = NSAttributedString(string: "789", attributes:stringAttributes3)

let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(string1)
mutableAttributedString.append(string2)
mutableAttributedString.append(string3)

label.attributedText = mutableAttributedString;

表示結果。

NSAttributedStringで指定できる属性

よく使いそうなものをピックアップしておきます。

  • .font
    • フォント。UIFontを指定
  • .foregroundColor
    • 文字色。UIColorを指定
  • .backgroundColor
    • 文字背景色。UIColorを指定
  • .kern
    • 文字間隔。floatを指定。2.0など
  • .underlineStyle
    • NSUnderlineStyleのrawValueを指定
    • NSUnderlineStyle.styleSingle.rawValueなど
  • .strokeColor
    • 縁取りの色。UIColorを指定
  • .strokeWidth
    • 縁取りの幅。floatを指定。
    • 正の値のときは縁取りの内側はclearColorになる。.foregroundの指定は無視される
    • 負の値のときは縁取りの内側は.foregroundColorになる(通常はこちらを使うと思う)
  • .shadow
    • 文字の影。NSShadowオブジェクトを指定