問題
StoryBoardやxibなどでUILabelに対してAttributedを設定した状態で
Swift
label.text = "新しい文字"
のように設定すると行間のスペースなど、Attributedで設定したものが反映されなくなってしまう。
解決策
UILabelを拡張してみる
extension UILabel {
func setAttributedTextString(string: String) {
self.attributedText = NSAttributedString(string: string,
attributes: self.attributedText?.attributes(at: 0, effectiveRange: nil))
}
}
実際に作成したsetAttributedTextString
を呼び出す。
label.setAttributedTextString(string: "新しい文字列")
これで変更前のattributedを保持したまま文字列のみ変更することができる。