LoginSignup
9
8

More than 5 years have passed since last update.

【 iOS】titleがAttributedのUIButtonの文字色を変える

Posted at

UIButtonの文字色を変えようと思ったがAtrributedで作られており、
文字色を変えたいだけなのにとてもハマってしまったのでメモ

変え方

// 変更したいButtonのtitleを取得してNSMutableAttributedStringに変換
let attributedString = NSMutableAttributedString(attributedString: self.attributedButton.attributedTitleForState(.Normal)!)

// 変更したい文字範囲の定義 (この場合は全部変えたいのでlength分のrangeを作成
let range = NSRange(location: 0, length: attributedString.length)

// 変更したい属性をDictionaryで渡す
attributedString.addAttributes(
    [
        NSForegroundColorAttributedName: UIColor.whiteColor()
    ],
    range: range
)

// 属性変更済みのNSMutableAtributeStringを設定して完了
self.attributedButton.setAttributedTitle(attributedString, forState: .Normal)

ちょっと長いので、もっとにスマートに変更できるやり方あれば知りたい...

ハマり所

1. Plainのtitleだった場合は以下の方法で変更できるが、Attributedの場合はできない

self.plainButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)

2. NSMutableAttributedStringに変換しないと属性を変更できない

UIButtonから取得するときはNSAttributedStringの状態なのでどうやっても変更できず積んでいた(常識っぽい

9
8
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
9
8