UIAppearance不会对以编程方式创build的UILabels生效

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

@interface UILabelHeadingBold : UILabel @end 

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

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

在我们的XIB中添加一个UILabel时,我们现在可以select类为UILabelHeadingBold的类,并且按照预期工作。 标签显示正确的字体和颜色,在我们的AppDelegate中指定。

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

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

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

有没有办法使UIAppearance能够在编程创build的UI元素上生效,还是只能在XIB中使用时才起作用?

从Apple文档:

为了支持外观定制,一个类必须符合UIAppearanceContainer协议,相关的访问器方法必须用UI_APPEARANCE_SELECTOR标记。

例如在UINavigationBar.htintColor被标记为UI_APPEARANCE_SELECTOR

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

但是在UILabel.h中,你可以看到textColorfont propertys没有用UI_APPEARANCE_SELECTOR标记,但是在Interface Builder中添加的时候它可以工作(在文档之后它根本不应该工作)。

简单的黑客工作对我来说没有任何问题是创build一个UIAppearance setter,修改UILabel属性的类别。

按照UIA的外观惯例,我创build了一个方法:

 - (void)setTextAttributes:(NSDictionary *)numberTextAttributes; { UIFont *font = [numberTextAttributes objectForKey:UITextAttributeFont]; if (font) { self.font = font; } UIColor *textColor = [numberTextAttributes objectForKey:UITextAttributeTextColor]; if (textColor) { self.textColor = textColor; } UIColor *textShadowColor = [numberTextAttributes objectForKey:UITextAttributeTextShadowColor]; if (textShadowColor) { self.shadowColor = textShadowColor; } NSValue *shadowOffsetValue = [numberTextAttributes objectForKey:UITextAttributeTextShadowOffset]; if (shadowOffsetValue) { UIOffset shadowOffset = [shadowOffsetValue UIOffsetValue]; self.shadowOffset = CGSizeMake(shadowOffset.horizontal, shadowOffset.vertical); } } 

在UILabel类别中:

 @interface UILabel (UISS) - (void)setTextAttributes:(NSDictionary *)numberTextAttributes UI_APPEARANCE_SELECTOR; @end 

我仍然试图找出为什么最初的制定者不工作。

@ robert.wijas解决scheme很棒!

对于iOS 7和更高版本,我不得不更新密钥,因为他使用的密钥已经被弃用了7次以上:

 - (void)setTextAttributes:(NSDictionary *)numberTextAttributes; { UIFont *font = [numberTextAttributes objectForKey:NSFontAttributeName]; if (font) { self.font = font; } UIColor *textColor = [numberTextAttributes objectForKey:NSForegroundColorAttributeName]; if (textColor) { self.textColor = textColor; } UIColor *textShadowColor = [numberTextAttributes objectForKey:NSShadowAttributeName]; if (textShadowColor) { self.shadowColor = textShadowColor; } NSValue *shadowOffsetValue = [numberTextAttributes objectForKey:NSShadowAttributeName]; if (shadowOffsetValue) { UIOffset shadowOffset = [shadowOffsetValue UIOffsetValue]; self.shadowOffset = CGSizeMake(shadowOffset.horizontal, shadowOffset.vertical); } }