1

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)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Hi @MuhammadTayyab, welcome to stack overflow. What is not working? What error messages are you getting? (eyeballing the optional there as a potential source of super fun times) – Slabgorb Jul 15 '19 at 19:12

3 Answers3

3

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?

Curtain Call LLC
  • 144
  • 1
  • 1
  • 11
0

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.

Terry
  • 88
  • 11
  • yes I set UIButton ttitleLabel font in AppDelegate method didFinishLaunchingWithOptions: but it's still not working – Muhammad Tayyab Jul 16 '19 at 03:24
  • Ok I think Apple deprecated the UIAppeance API for changing the font... you can try the Curtain Call LLC's solution, it should work for you. – Terry Jul 17 '19 at 08:22
0

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
    }
}
Litehouse
  • 864
  • 8
  • 14