【问题标题】:Changing all UIButton font更改所有 UIButton 字体
【发布时间】:2014-04-05 22:17:43
【问题描述】:

我一直在寻找将近 2 个小时,但找不到这个问题的可靠答案。

我尝试使用外观机制,但您似乎无法使用它更改字体。

我查看了此处建议的答案: How to change all UIButton fonts to custom font

有3个答案:

  1. 使用 buttonOutlet,但这需要一个数组,整个项目中的所有按钮都链接到该数组。
  2. 使用类别,但从我读到的内容来看,强烈建议不要在 为了覆盖现有的方法。
  3. 使用从 UIButton 派生的自定义类,但是当我尝试使用提供的类时 并且在界面生成器中设置它没有任何反应,这让我相信你需要以编程方式添加你的按钮。

编辑:如果您实现 - (id)initWithCoder:(NSCoder *)aDecoder uibutton 方法,则使用答案 3 这使您可以简单地更改界面生成器中的类,但您仍然需要为项目中的所有按钮执行此操作。

有人有什么新想法吗?

【问题讨论】:

  • 用3,你是不是把按钮的类改成你在Interface Builder中的自定义类了?
  • 我用 3 解决了我的问题。我需要实现 - (id)initWithCoder:(NSCoder *)aDecoder 方法。这是被调用的..
  • 这和xcode IDE有什么关系????
  • [[UIButton appearance] setFont:[UIFont fontWithName:@"AmericanTypewriter" size:10.0]]; 确实有效,尽管 setFont 已被弃用。

标签: ios uibutton


【解决方案1】:
for (UIButton *button in self.view.subviews) {
        if ([button isKindOfClass:UIButton.class]) {
            button.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:14.0f];
        }
    }

如果您无法使链接的问题发挥作用,则可以使用。

【讨论】:

    【解决方案2】:

    您可以使用 UIAppearance 自定义任何控件的视图。您可以在NSHipster 上的这篇非常有用的文章中查看更多信息。

    【讨论】:

    • setFont on UIButton 在 iOS3 中已被弃用,但可能很危险。
    • UIButton 外观没有字体功能
    【解决方案3】:

    出于某种只有苹果大神知道的原因,

    [[[UIButton appearance] titleLabel] setFont:fontButton];
    

    不起作用。在 swift 中找到了一个对我有用的解决方案

    How to set UIButton font via appearance proxy in iOS 8?

    Objective-C 中的解决方案是创建一个像这样暴露 titleLabel 字体的类别

    UIButton+TitleLabelFont.h

    #import <UIKit/UIKit.h>
    
    @interface UIButton (TitleLabelFont)
    
    @property (strong, nonatomic) UIFont *titleFont;
    
    @end
    

    UIButton+TitleLabelFont.m

    #import "UIButton+TitleLabelFont.h"
    
    @implementation UIButton (TitleLabelFont)
    
    - (UIFont *)titleFont {
    
        return self.titleLabel.font;
    }
    
    - (void)setTitleFont:(UIFont *)titleFont {
    
        self.titleLabel.font = titleFont;
    }
    
    @end
    

    然后在源中导入类别 UIButton+TitleLabelFont 来简单地设置外观

    #import "UIButton+ASLAdditions.h"
    

    你可以设置外观

    [UIButton appearance].titleFont = fontButton;
    

    经过测试并完美地为我工作

    【讨论】:

      【解决方案4】:

      在 Swift3 中

      UIButton.appearance().titleLabel?.font = font
      

      【讨论】:

        猜你喜欢
        • 2011-10-04
        • 2016-09-07
        • 2012-12-19
        • 1970-01-01
        • 2022-09-24
        • 2023-03-04
        • 2022-01-02
        • 2017-05-06
        相关资源
        最近更新 更多