LoginSignup
2
2

More than 5 years have passed since last update.

UIAppearanceが設定されているとNSAttributedStringが正しく反映されない

Posted at

問題点

UIAppearanceが設定されているとNSAttributedStringで設定した一部項目が反映されない現象
※検証用プロジェクトを作っている最中に気付いたのですが、IBで置いたビューだと上記問題が発生するようです。

再現コード

AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        UILabel.appearance().textColor = UIColor.orangeColor()
        return true
    }
}
ViewController.swift
class ViewController: UIViewController {

    @IBOutlet weak var ibLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let baseAttr = [
            NSForegroundColorAttributeName: UIColor.lightGrayColor(),
            NSFontAttributeName: UIFont.systemFontOfSize(10),
        ]


        let linkAttr = [
            NSForegroundColorAttributeName: UIColor.blueColor(),
            NSFontAttributeName: UIFont.italicSystemFontOfSize(10),
        ]

        let texts = ["message", "http://qiita.com", "message"]
        let attributedText = NSMutableAttributedString()
        attributedText.appendAttributedString(NSAttributedString(string: texts[0], attributes: baseAttr))
        attributedText.appendAttributedString(NSAttributedString(string: texts[1], attributes: linkAttr))
        attributedText.appendAttributedString(NSAttributedString(string: texts[2], attributes: baseAttr))


//        self.ibLabel.textColor = nil  // コメントアウトするとUIAppearanceの設定が優先される
        self.ibLabel.attributedText = attributedText
        self.ibLabel.sizeToFit()
    }
}

対応策

対応としては以下の2点が考えられます。

  1. NSAttributedStringを設定する直前でUIAppearanceで指定したプロパティにnilを代入する
  2. UIAppearanceに指定するビュークラスを被らないようカスタムクラスにする

基本的には1.の方法で、nilを代入する処理を差し込みづらい?とき場合は、2.の方法で対応する流れでいいと思います。
今回は1.の方法で解決しました。

2
2
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
2
2