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

Hlu*_*ung 1 uibutton ios uiappearance swift

我试图设置UIButtonvia appearance proxy 的字体.但它似乎没有用.这是我试过的.

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

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

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

小智 9

与主题应用程序有同样的问题.

1.添加此扩展程序

// UIButton+TitleLabelFont.swift

import UIKit

extension UIButton {
    var titleLabelFont: UIFont! {
        get { return self.titleLabel?.font }
        set { self.titleLabel?.font = newValue }
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

3.在app delegate中删除主题设置

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

    // ...

    return true
}
Run Code Online (Sandbox Code Playgroud)

如果您之前正在预装东西(lazy var来自故事板的VC),那么最好不要使用app委托设置覆盖初始值设定项中的主题内容,如下所示:

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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)