如何在 appearance() 中更改 UIButton titlelabel 字体样式和大小?

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

我正在使用下面的代码,但它不起作用。谁能帮我解决这个问题?

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

如果你想设置一个通用的字体,你可以在方法didFinishLaunchingWithOptions:中调用你的代码UIButton.appearance().titleLabel?.font = UIFont(name: "Roboto-Regular", size: 20.0) from AppDelegate.

好的,试试这个:

转到 AppDelegate 并粘贴这个-

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

然后在此处添加"Theme.apply()"(仍在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
}

我用 Courier 字体做的,它对我有用。我认为您需要确保您的字体已安装在您的应用程序中。

这是我从这里得到的:How to set UIButton font via appearance proxy in iOS 8?

使用 UIAppearance 设置 UIButton 的字体如下:

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

您可以将上述代码添加到您的 AppDelegate 方法 application(_:, didFinishLaunchingWithOptions:) 中,或者任何适合为您的应用程序设置主题的地方。

UIViewController.viewDidLoad 中将按钮实例 titleLabeladjustsFontForContentSizeCategory 属性 设置为真。

class ExampleVC: UIViewController

    @IBOutlet weak var btnOkay: UIButton!

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