如何为整个应用程序设置自定义字体?

时间:2011-09-30 07:14:42

标签: iphone objective-c ios uiview custom-font

有没有办法在iphone objective-c中将全局字体[新自定义字体]应用于整个应用程序。

我知道我们可以使用以下方法为每个标签设置字体

[self.titleLabel setFont:[UIFont fontWithName:@"FONOT_NAME" size:FONT_SIZE]];

但是我想改变整个应用程序。 如果有人知道,请帮助我。

5 个答案:

答案 0 :(得分:5)

显然,要完全更改所有UILabel,您需要在UILabel上设置一个类别并更改默认字体。所以这里有一个解决方案:

创建一个文件CustomFontLabel.h

@interface UILabel(changeFont)
- (void)awakeFromNib;
-(id)initWithFrame:(CGRect)frame;
@end

创建一个文件CustomFontLabel.m

@implementation UILabel(changeFont)
- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setFont:[UIFont fontWithName:@"Zapfino" size:12.0]];
}

-(id)initWithFrame:(CGRect)frame
{
    id result = [super initWithFrame:frame];
    if (result) {
        [self setFont:[UIFont fontWithName:@"Zapfino" size:12.0]];
    }
    return result;
}
@end

现在......在任何视图控制器中,您需要这些自定义字体标签,只需包含在顶部:

#import "CustomFontLabel.h"

这就是全部 - 祝你好运

答案 1 :(得分:3)

Ican的类别解决方案可能只是为了节省一天。但是,避免使用类别覆盖现有方法,如苹果解释: Avoid Category Method Name Clashes

  

...如果在类别中声明的方法的名称与原始类中的方法相同,或者在同一个类(或甚至是超类)中的另一个类别中的方法相同,则行为未定义为在运行时使用哪个方法实现。 ...

另请注意,覆盖-(id) init;比覆盖-(id)initWithFrame:(CGRect)frame更安全。单击UIButtons上的标签时,您不会遇到未接收触摸事件的问题。

答案 2 :(得分:1)

这是你的意思吗?

@interface GlobalMethods
+(UIFont *)appFont;
@end

@implementation GlobalMethods
+(UIFont *)appFont{
    return [UIFont fontWithName:@"someFontName" size:someFontSize];
}
@end

...
[self.titleLabel setFont:[GlobalMethods appFont]];

如果您想以某种方式自动完成(不在每个控件上使用setFont),我认为不可能。

答案 3 :(得分:0)

如果您可以将应用程序(或此特定功能)限制为iOS 5,那么可以使用新的API来非常方便地为默认UI设置外观。我不能给你详细信息,因为在我写这篇文章的时候他们还在NDA之下。查看iOS 5 beta SDK以了解更多信息。

答案 4 :(得分:0)

CustomLabel.h

#import <UIKit/UIKit.h>

@interface VVLabel : UILabel

@end

CustomLabel.m

#import "CustomLabel.h"
#define FontDefaultName @"YourFontName"
@implementation VVLabel
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder: aDecoder];
    if (self) {
        // Initialization code
        // Static font size
        self.font = [UIFont fontWithName:FontDefaultName size:17];


        // If you want dynamic font size (Get font size from storyboard / From XIB then put below line)
        self.font = [UIFont fontWithName:FontDefaultName size:self.font.pointSize];

    }
    return self;
}
相关问题