使用UIAppearance代理设计UILabel

问题描述:

我的应用程序中有许多UILabel元素,我正在寻找一种使用UIAppearance代理对象设计风格的简单方法。我目前的做法是创建UILabel的不同子类,并配备UI_APPEARANCE_SELECTOR装饰器,以便通过[UILabelSubclass appearance]调用访问。你可以找到我使用的来源herehere。 问题是我不想设置字体大小,而只是依赖于故事板中定义大小的字体系列。使用UIAppearance代理设计UILabel

如何在子类中设置它?

我认为你可以在你的子类是这样尝试:

UIFont *newFont = [UIFont fontWithName:@"YourFontName" size:self.font.pointSize]; 
self.font = newFont 

这里有一个简单的类别,与UIAppearance代理工作:

@interface UILabel (FontName) 

- (void)setFontName:(NSString *)name UI_APPEARANCE_SELECTOR; 

@end 


@implementation UILabel (FontName) 

- (void)setFontName:(NSString *)name { 
    self.font = [UIFont fontWithName:name size:self.font.pointSize]; 
} 

@end 
+0

这也是一个很好的解决方案。我标记了另一个,只是因为与我正在执行的内容有点接近。 – Claus

+0

这不起作用 – JAHelia

+0

我可以证实这对我有用。谢谢! – Emilio

多亏了这个帖子,也从一个博客帖子Peter Steinberger(http://petersteinberger.com/)我能够找到适合自己的东西:

@interface UILabel (FontAppearance) 
@property (nonatomic, copy) UIFont *appearanceFont UI_APPEARANCE_SELECTOR; 
@end 


@implementation UILabel (FontAppearance) 
- (void)setAppearanceFont:(UIFont*)font 
{ 
    [self setFont:font]; 
} 

-(UIFont*)appearanceFont 
{ 
    return [self font]; 
} 
@end