iosswiftuibuttonuiappearance

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)

Solution

  • 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?