17
15

More than 5 years have passed since last update.

AttributedTextを簡単に書けるExtension

Last updated at Posted at 2019-03-31

UILabelとかUITextViewattributedTextはそのまま書くと結構めんどくさいので楽に書けるextensionを作りました。

もっとこうしたら良いんじゃないのとかダメじゃんて部分あったらコメントで教えてもらえるとありがたいです。

最初に、どう書けるかを書いときます

使い方

let atrStr1 = "aaa".attribute()
    .font(.boldSystemFont(ofSize: 12))
    .textColor(.blue)
    .spacing(5)

let atrStr2 = "bbb".attribute()
    .font(.systemFont(ofSize: 15))
    .textColor(.red)
    .spacing(1)

let atrStr3 = "ccc".attribute()
    .font(.systemFont(ofSize: 12))
    .textColor(.green)
    .spacing(10)

label.attributedText = atrStr1 + atrStr2 + atrStr3

Screen Shot 2019-03-31 at 20.32.41.png

実装法

extension String {

    func attribute() -> NSMutableAttributedString {
        return NSMutableAttributedString(string: self)
    }
}

extension NSMutableAttributedString {

    static func + (left: NSMutableAttributedString, right: NSMutableAttributedString) -> NSMutableAttributedString {
        left.append(right)
        return left
    }

    func font(_ font: UIFont) -> Self {
        addAttribute(.font, value: font, range: NSMakeRange(0, string.count))
        return self
    }

    func textColor(_ color: UIColor) -> Self {
        addAttribute(.foregroundColor, value: color, range: NSMakeRange(0, string.count))
        return self
    }

    func backgroundColor(_ color: UIColor) -> Self {
        addAttribute(.backgroundColor, value: color, range: NSMakeRange(0, string.count))
        return self
    }

    func baseLineOffset(_ offset: CGFloat) -> Self {
        addAttribute(.baselineOffset, value: offset, range: NSMakeRange(0, string.count))
        return self
    }

    func underline(color: UIColor, style: NSUnderlineStyle) -> Self {
        let attributes: [NSAttributedString.Key : Any] = [
            NSAttributedString.Key.underlineStyle : style.rawValue,
            NSAttributedString.Key.underlineColor : color
        ]
        addAttributes(attributes, range: NSMakeRange(0, string.count))
        return self
    }

    func spacing(_ spacing: CGFloat) -> Self {
        addAttribute(.kern, value: spacing, range: NSMakeRange(0, string.count))
        return self
    }
}

個人的に演算子のオーバーロードのところとかが気になっています

参考
https://qiita.com/roba4coding/items/7a5decc7e4f6137fcc88

17
15
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
15