Muhammad Tayyab
Muhammad Tayyab

Reputation: 67

How to change UIButton titlelabel fonts style and size in appearance()?

I am using the code below but it's not working. Can anyone help me to resolve this problem?

UIButton.appearance().titleLabel?.font = UIFont(name: "Roboto-Regular", size: 20.0)

Upvotes: 1

Views: 745

Answers (3)

Litehouse
Litehouse

Reputation: 904

Set the UIButton's font with UIAppearance as follows:

label = UILabel.appearance(whenContainedInInstancesOf: [UIButton.self])
label.font = UIFont.systemFont(ofSize: 20)

You may add the above code in your AppDelegate's method application(_:, didFinishLaunchingWithOptions:), or wherever it is appropriate to set the theme for your application.

In UIViewController.viewDidLoad set adjustsFontForContentSizeCategory property of the button instance's titleLabel to true.

class ExampleVC: UIViewController

    @IBOutlet weak var btnOkay: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        btnOkay.titleLabel?.adjustsFontForContentSizeCategory = true
    }
}

Upvotes: 0

Curtain Call LLC
Curtain Call LLC

Reputation: 144

Ok, try this instead:

Go to the AppDelegate and paste this-

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


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: "Courier", size:20.0)

        // other UIButton customizations
    }
}

And then add "Theme.apply()" here (still in the AppDelegate):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    //UIApplication.shared.statusBarStyle = .lightContent

    Theme.apply() // ADD THIS
    return true
}

I did it with Courier font and it worked for me. I think you need to make sure your font is installed in your app.

This is where I got it from: How to set UIButton font via appearance proxy in iOS 8?

Upvotes: 3

Terry
Terry

Reputation: 108

If you want to set a font generally, you can call your code UIButton.appearance().titleLabel?.font = UIFont(name: "Roboto-Regular", size: 20.0) in the method didFinishLaunchingWithOptions: from AppDelegate.

Upvotes: 0

Related Questions