LoginSignup
3
0

More than 3 years have passed since last update.

UILabelのAttributedが反映されない Swift

Last updated at Posted at 2019-07-27

問題

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を保持したまま文字列のみ変更することができる。

3
0
0

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
3
0