【问题标题】:How to change UIButton titlelabel fonts style and size in appearance()?如何在外观()中更改 UIButton 标题标签字体样式和大小?
【发布时间】:2019-11-24 11:49:27
【问题描述】:

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

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

【问题讨论】:

  • 嗨@MuhammadTayyab,欢迎来到堆栈溢出。什么不工作?您收到什么错误消息? (将那里的可选项视为超级有趣时光的潜在来源)

标签: ios swift uibutton uiappearance


【解决方案1】:

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

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

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

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

class ExampleVC: UIViewController

    @IBOutlet weak var btnOkay: UIButton!

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

【讨论】:

    【解决方案2】:

    好的,试试这个:

    转到 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?

    【讨论】:

    • 谢谢谢幕有限责任公司。此解决方案适用于我的工作
    • @MuhammadTayyab 哦,太棒了! :)
    【解决方案3】:

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

    【讨论】:

    • 是的,我在 AppDelegate 方法中设置了 UIButton ttitleLabel 字体 didFinishLaunchingWithOptions: 但它仍然无法正常工作
    • 好的,我认为 Apple 已弃用 UIAppeance API 来更改字体...您可以尝试 Curtain Call LLC 的解决方案,它应该适合您。
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多