如何在一个命令中更改所有标签字体

时间:2012-03-09 13:52:10

标签: iphone objective-c xcode ipad

如果我有3个名为total,score和name的标签,我想更改文本的字体我使用此命令

[total setFont:[UIFont fontWithName:@"Times New Roman" size:22]];
[score setFont:[UIFont fontWithName:@"Times New Roman" size:22]];
[name setFont:[UIFont fontWithName:@"Times New Roman" size:22]];

如果我在一个视图中有超过20个标签,并且所有人都有不同的名称,如总得分名称,那该怎么办?

是否有更短的方法将所有字体的字体更改为相同的字体类型?

5 个答案:

答案 0 :(得分:10)

快速枚举..

 for( UIView *view in self.subviews)
    {
    if([view isKindOfClass:[UILabel Class]])
    {
    [(UILabel *)view setFont:[UIFont fontWithName:@"Times New Roman" size:22]];

    }
    }

答案 1 :(得分:2)

对于特定标签;

    for( UIView *v in self.view.subviews) {
        if([v isKindOfClass:[UILabel Class]]) {
            if (v.tag == 1453)
               [(UILabel *)v setFont:[UIFont fontWithName:@"Times New Roman" size:22]];
        }
    }

答案 2 :(得分:0)

in .h

  

UIFont * myCustomFont;

in .m

  

myCustomFont = [UIFont fontWithName:@“Times New Roman”尺寸:22];

     

[Name setFont:myCustomFont]; //名称是您的UILabel //

或者在prifix.pch文件中直接完成项目。

答案 3 :(得分:0)

这种效果也可以通过UILabel类别使用Method Swizzling技术来实现: http://darkdust.net/writings/objective-c/method-swizzling#Step_2:_Create_the_wrapper_method

部首:

#import <UIKit/UIKit.h>

@interface UILabel (Swizzling)

- (UIFont *)swizzledFont;

@end

实现:

#import "UILabel+Swizzling.h"
#import <objc/runtime.h>

@implementation UILabel (Swizzling)

- (UIFont *)swizzledFont
{
    return [UIFont fontWithName:@"SourceSansPro-Light" size:[[self swizzledFont] pointSize]];
}

+ (void)load
{
    Method original, swizzled;

    original = class_getInstanceMethod(self, @selector(font));
    swizzled = class_getInstanceMethod(self, @selector(swizzledFont));
    method_exchangeImplementations(original, swizzled);
}

@end

答案 4 :(得分:0)

覆盖UIFont

创建UIFont+SytemFontOverride.h

#import <UIKit/UIKit.h>

@interface UIFont (SytemFontOverride)
@end

UIFont+SytemFontOverride.m

#import "UIFont+SytemFontOverride.h"
@implementation UIFont (SytemFontOverride)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"Bryant-Bold" size:fontSize];
}

+ (UIFont *)systemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"Bryant-Regular" size:fontSize];
}

#pragma clang diagnostic pop

@end

相应地更改字体名称。