UILabel
とかUITextView
のattributedText
はそのまま書くと結構めんどくさいので楽に書ける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
実装法
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
}
}
個人的に演算子のオーバーロードのところとかが気になっています