問題点
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点が考えられます。
-
NSAttributedString
を設定する直前でUIAppearance
で指定したプロパティにnil
を代入する -
UIAppearance
に指定するビュークラスを被らないようカスタムクラスにする
基本的には1.
の方法で、nil
を代入する処理を差し込みづらい?とき場合は、2.
の方法で対応する流れでいいと思います。
今回は1.
の方法で解決しました。