如何将所有UIButton字体更改为自定义字体?

vbu*_*vic 4 iphone xcode fonts interface-builder

有没有办法做到这一点?我希望有一个自定义字体,我已经下载以显示在UIButton上.

Dee*_*olu 7

如果你使用 IBOutletCollection那么这应该是直接的.

@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *buttons;
Run Code Online (Sandbox Code Playgroud)

将按钮连接到此插座集合,然后使用,一次更改字体,

[self setValue:[UIFont fontWithName:@"Helvetica" size:30] forKeyPath:@"buttons.font"];
Run Code Online (Sandbox Code Playgroud)


Cyp*_*ian 5

你可以做的一种方法是继承UIButton设置你想要的字体并使用你的子类而不是UIButton.

编辑

//
//  MyUIButton.h
//

@interface MyUIButton : UIButton {

}
+ (id)buttonWithType:(UIButtonType)buttonType;
@end

//
//  MyUIButton.m
//


#import "MyUIButton.h"


@implementation MyUIButton

+ (id)buttonWithType:(UIButtonType)buttonType{
   UIButton *button = [UIButton buttonWithType:buttonType];
   [[button titleLabel] setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12]];
   return button;
}

@end

Then just use it like this:

[MyUIButton buttonWithType:UIButtonTypeCustom]
Run Code Online (Sandbox Code Playgroud)

您可以尝试的另一件事是为UIButton编写一个类别并在那里覆盖它.

EDIT2

    //
    //  UIButton+Font.h
    //

#import <Foundation/Foundation.h>

@interface UIButton (DefaultFontExtension)
+ (id)buttonWithType:(UIButtonType)buttonType;
@end


    //
    //  UIButton+Font.m
    //

#import "UIButton+Font.h"

@implementation UIButton (DefaultFontExtension)

+ (id)buttonWithType:(UIButtonType)buttonType{
       UIButton *button = [UIButton buttonWithType:buttonType];
       [[button titleLabel] setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12]];
       return button;
    }

@end
Run Code Online (Sandbox Code Playgroud)

现在只需导入"UIButton + Font.h",它将覆盖默认的UIButton设置.