如何在iOS 8中通过外观代理设置UIButton字体?

我试图通过外观代理设置UIButton的字体。 但似乎没有工作。 这是我的尝试。

UIButton.appearance().titleFont = UIFont(name: FONT_NAME_DEFAULT, size:20.0) UIButton.appearance().titleLabel?.font = UIFont(name: FONT_NAME_DEFAULT, size:20.0)

如何在iOS 8中通过外观代理设置UIButton字体?

编辑 :在vaberer的链接中find:“我很惊讶,UIButton没有任何UI_APPEARANCE_SELECTOR属性,但符合UIAppearance协议。

有一个主题的应用程序相同的问题。

1.添加这个扩展名

 // UIButton+TitleLabelFont.swift import UIKit extension UIButton { var titleLabelFont: UIFont! { get { return self.titleLabel?.font } set { self.titleLabel?.font = newValue } } } 

2.然后设置UIButton外观原型对象

 class Theme { static func apply() { applyToUIButton() // ... } // It can either theme a specific UIButton instance, or defaults to the appearance proxy (prototype object) by default static func applyToUIButton(a: UIButton = UIButton.appearance()) { a.titleLabelFont = UIFont(name: FONT_NAME_DEFAULT, size:20.0) // other UIButton customizations } } 

3.在应用程序委托中放置主题设置

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Theme.apply() // ... return true } 

如果你之前正在预加载东西(从故事板中的lazy var VC),可能会更好,而不是使用应用程序委托设置主题的东西在一个重写初始化如下所示:

 private var _NSObject__Theme_apply_token: dispatch_once_t = 0 extension NSObject { override public class func initialize() { super.initialize() // see also: https://stackoverflow.com/questions/19176219/why-am-i-getting-deadlock-with-dispatch-once var shouldRun = false dispatch_once(&_NSObject__Theme_apply_token) { shouldRun = true } if shouldRun { Theme.apply() } } } 

您正试图在UIButton设置UILabel的字体。 由于UILabel没有标记为UI_APPEARANCE_SELECTOR。 你不能这样做。

查看UIA外观元素列表: 可以通过UIAppearance代理设置哪些属性?