如何在iOS 8中通过外观代理设置UIButton字体? [英] How to set UIButton font via appearance proxy in iOS 8?

查看:124
本文介绍了如何在iOS 8中通过外观代理设置UIButton字体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过外观代理设置UIButton的字体.但这似乎不起作用.这就是我尝试过的.

I tried to set the font of UIButton via appearance proxy. But it doesn't seem to work. This is what I tried.

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字体?

How to set UIButton font via appearance proxy in iOS 8 ?

编辑:在vaberer的

EDIT: Found in vaberer's link: "I'm surprised that UIButton doesn't have any UI_APPEARANCE_SELECTOR properties, yet conforms to the UIAppearance protocol."

推荐答案

具有主题主题的应用程序也存在同样的问题.

Had the same problem with a theme-able app.

// UIButton+TitleLabelFont.swift

import UIKit

extension UIButton {
    var titleLabelFont: UIFont! {
        get { return self.titleLabel?.font }
        set { self.titleLabel?.font = newValue }
    }
}

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

2. Then setup the UIButton appearance prototype object

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),那么最好不使用应用程序委托在覆盖初始化程序中设置主题内容,如下所示:

If you're preloading stuff (lazy var VCs from storyboards) earlier, it may be better to instead of using app delegate setup the theme stuff in an override initializer like so:

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()
        }
    }
}

这篇关于如何在iOS 8中通过外观代理设置UIButton字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆