Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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)

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

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."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Had the same problem with a theme-able app.

1. Add this extension

// UIButton+TitleLabelFont.swift

import UIKit

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

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. Drop the theme setup in app delegate

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

    // ...

    return true
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...