UIAppearance对以编程方式创建的UILabels没有生效 [英] UIAppearance not taking effect on UILabels created programmatically

查看:235
本文介绍了UIAppearance对以编程方式创建的UILabels没有生效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们已经扩展了UILabel,以便能够在我们的应用程序中为给定标签类型的所有用途应用标准字体和颜色。例如。

  @interface UILabelHeadingBold:UILabel 
@end

在我们的AppDelegate中,我们应用这样的字体和颜色

  [ [UILabelHeadingBold外观] setTextColor:< some color>]; 
[[UILabelHeadingBold appearance] setFont:< some font>];

在我们的XIB中添加UILabel时,我们现在可以选择类型为UILabelHeadingBold的类,并且它按预期工作。标签显示正确的字体和颜色,如我们的AppDelegate中所指定。



但是,如果我们以编程方式创建标签,例如。

  UILabelHeadingBold * headingLabel = [[UILabelHeadingBold alloc] initWithFrame:CGRectMake(10,10,100,30)]; 
[self.mainView addSubview:headingLabel];

UILabel未获得预期的字体/颜色。我们必须手动应用这些属性。



有没有办法让UIAppearance在编程创建的UI元素上生效,还是只在XIB中使用时才有效?


为了支持外观自定义,类必须符合到
UIAppearanceContainer协议和相关的访问者方法必须是
,标记为UI_APPEARANCE_SELECTOR。


例如在 UINavigationBar.h tintColor 标有 UI_APPEARANCE_SELECTOR

  @property(非原子,保留)UIColor * tintColor UI_APPEARANCE_SELECTOR; 

但是在UILabel.h中你可以看到 textColor font propertys没有用UI_APPEARANCE_SELECTOR标记,但是在Interface Builder中添加时它会起作用(遵循文档它根本不起作用)。


We have extended UILabel to be able to apply standard fonts and colors for all uses of a given label type in our apps. Eg.

@interface UILabelHeadingBold : UILabel
@end

In our AppDelegate, we apply fonts and colors like this

[[UILabelHeadingBold appearance] setTextColor:<some color>];
[[UILabelHeadingBold appearance] setFont:<some font>];

When adding a UILabel in our XIB's, we can now select the class to be of type UILabelHeadingBold, and it works as expected. The label is shown with the correct font and color, as specified in our AppDelegate.

However, if we create a label programmatically, eg.

UILabelHeadingBold *headingLabel = [[UILabelHeadingBold alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
[self.mainView addSubview:headingLabel];

the UILabel does not get the expected font/color applied. We have to manually apply these attributes.

Is there a way to make UIAppearance take effect on programatically created UI elements, or does it only work when used within XIB's?

解决方案

From Apple documentation :

To support appearance customization, a class must conform to the UIAppearanceContainer protocol and relevant accessor methods must be marked with UI_APPEARANCE_SELECTOR.

For example in UINavigationBar.h, tintColor is marked with UI_APPEARANCE_SELECTOR

@property(nonatomic,retain) UIColor *tintColor UI_APPEARANCE_SELECTOR;

But in UILabel.h you can see that the textColor and font propertys are not marked with UI_APPEARANCE_SELECTOR but somehow it works when added in Interface Builder (following the documentation it shouldn't work at all).

这篇关于UIAppearance对以编程方式创建的UILabels没有生效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆