使用 UIAppearance 代理设置 UILabel 样式

Posted

技术标签:

【中文标题】使用 UIAppearance 代理设置 UILabel 样式【英文标题】:Styling UILabel using UIAppearance proxy 【发布时间】:2013-07-02 17:51:33 【问题描述】:

我的应用程序中有许多 UILabel 元素,我正在寻找一种简单的方法来使用 UIAppearance 代理对象设置它们的样式。我目前的方法是创建配备 UI_APPEARANCE_SELECTOR 装饰器的 UILabel 的不同子类,以便通过[UILabelSubclass appearance] 调用可以访问。您可以找到我用作参考的来源here 和here。 问题是我不想设置字体大小,而只想设置依赖于情节提要中定义的大小的字体系列。

如何在子类中设置?

【问题讨论】:

【参考方案1】:

这是一个与 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

【讨论】:

这也是一个很好的解决方案。我标记另一个只是因为它更接近我正在实施的内容。【参考方案2】:

我认为你可以在你的子类中尝试类似:

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

【讨论】:

【参考方案3】:

感谢这篇文章,以及来自 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

【讨论】:

以上是关于使用 UIAppearance 代理设置 UILabel 样式的主要内容,如果未能解决你的问题,请参考以下文章

检测自定义按钮的 UIAppearance 代理中的更改

限制 UIAppearance 代理范围

使用 UIAppearance 代理自定义字体时,MFMailComposeViewController 不起作用

如何使 UIAppearance 代理适用于以编程方式创建的视图?

UIPageControl + UIAppearance

如何在MonoTouch中为继承的视图创建UIAppearance代理?