如何为视图中的所有标签设置自定义字体?

时间:2013-03-19 12:11:11

标签: ios xcode fonts uilabel

我想为我的完整视图设置自定义字体

我已经提到了以下内容 How do I set a custom font for the whole application?

但这仅表示标签的字体类型和字体大小 目前我正在为所有增加冗余的标签使用以下代码段。

label.textColor = [UIColor blueColor];
[label setBackgroundColor:[UIColor clearColor]];

是否可以以类似的方式添加文字颜色和背景颜色?

3 个答案:

答案 0 :(得分:3)

试试这个

-(void)changeFont:(UIView *) view{
    for (id View in [view subviews]) {
        if ([View isKindOfClass:[UILabel class]]) { 
                [View setFont:[UIFont fontWithName:@"Candara" size:26]];
                View.textColor = [UIColor blueColor];
                [View setBackgroundColor:[UIColor clearColor]];
        }
        if ([View isKindOfClass:[UIView class]]) {
            [self changeFont:View];
        }
    }
}

调用此方法并传递view

答案 1 :(得分:2)

如果您使用的是iOS 5+并且标签位于自定义视图中(或者可以将其置于自定义视图中),那么您可以使用UIAppearanceUIAppearanceContainer。它们是针对这种情况制作的。

相关方法是+appearanceWhenContainedIn:,当您定位的视图类包含在给定类的视图中时,它允许您设置外观(字体,颜色,背景图像等)。

// Set appearance of UILabels within MyViews
[[UILabel appearanceWhenContainedIn:[MyView class], nil] 
    setTextColor:[UIColor greenColor]];

[[UILabel appearanceWhenContainedIn:[MyView class], nil] 
    setFont:[UIFont fontWithName:@"SourceCodePro-Black" size:24]];

我把它放到app委托中,但你可以把它放在其他地方。这将更改类UILabel视图中的所有MyView个实例的外观。

有关详细信息,请查看会话114的WWDC 2011视频。

enter image description here

答案 2 :(得分:1)

category创建一个label,如“

    @interface UILabel(SMLabelCatogary)
    - (void) setCustomLabelDesign;
    @end

    @implementation UILabel(SMLabelCatogary)
    - (void) setCustomLabelDesign{
        label.textColor = [UIColor blueColor];
        [label setBackgroundColor:[UIColor clearColor]];
    }
    @end

现在使用您的标签(setCustomLabelDesign)调用[label setCustomLabelDesign],以按照此标准自定义。