⚠️大幅に変更が加えられた ver1.0.0 がリリースされました。
詳細はこちら
はじめに
SwiftでAttributedStringを使うとき、NSFontAttributeName
などを直打ちしたり、装飾したい範囲を指定するのがめんどうくさいと感じていたので、SwiftyAttributedStringというライブラリを作成しました。
改善点などがあったら是非教えてください。
特徴
-
String
から簡単にNSMutableAttributedString
を作成できる -
NSFontAttributeName
などを直打ちすることなく、補完が効いた状態で書くことが可能
let attribute = Attribute(value: .font(.systemFont(ofSize: 16)))
textView.attributedText = "SwiftyAttributedString".add(attribute: attribute)
- 装飾範囲の指定が簡単
// "Swifty"の部分だけオレンジ
let attribute = Attribute(value: .foregroundColor(.orange),
range: .portion(of: .string("Swifty")))
textView.attributedText = "SwiftyAttributedString".add(attribute: attribute)
// 全てに適応させる場合(rangeは省略可能)
let attribute = Attribute(value: .foregroundColor(.orange),
range: .all)
textView.attributedText = "SwiftyAttributedString".add(attribute: attribute)
- 複数の装飾を簡潔に記述できる
let attribute = Attribute(values: [.font(.systemFont(ofSize: 16)),
.foregroundColor(.red),
.underlineStyle(1.0),])
textView.attributedText = "SwiftyAttributedString".add(attribute: attribute)
- メソッドチェーン
textView.attributedText = "SwiftyAttributedString"
.add(attribute: Attribute(value: .font(.systemFont(ofSize: 16))))
.add(attribute: Attribute(value: .foregroundColor(.orange),
range: .portion(of: .string("String"))))
.add(attribute: Attribute(values: [.underlineStyle(1.0),
.foregroundColor(.blue)],
range: .portion(of: .string("Attributed"))))

導入
Carthage
Cartfile
に以下を追記
Cartfile
github "touyu/SwiftyAttributedString"
Terminal
$ carthage update --platform iOS
CocoaPods
Podfile
に以下を追記
Podfile
pod 'SwiftyAttributedString'
Terminal
$ pod install
例
textView.attributedText = "SwiftyAttributedString"
.add(attribute: Attribute(value: .font(.systemFont(ofSize: 16))))
.add(attribute: Attribute(value: .font(.boldSystemFont(ofSize: 16)),
range: .portion(of: .string("String"))))
.add(attribute: Attribute(value: .foregroundColor(.blue),
range: .portion(of: .string("Swifty"))))
.add(attribute: Attribute(value: .foregroundColor(.red),
range: .portion(of: .string("Attributed"))))
.add(attribute: Attribute(value: .foregroundColor(.orange),
range: .portion(of: .string("String"))))
.add(attribute: Attribute(value: .underlineStyle(1.0),
range: .portion(of: .string("Attributed"))))