cki*_*sen 17 appearance ios uiappearance
我们扩展了UILabel,以便能够在我们的应用程序中为给定标签类型的所有用途应用标准字体和颜色.例如.
@interface UILabelHeadingBold : UILabel
@end
Run Code Online (Sandbox Code Playgroud)
在我们的AppDelegate中,我们应用这样的字体和颜色
[[UILabelHeadingBold appearance] setTextColor:<some color>];
[[UILabelHeadingBold appearance] setFont:<some font>];
Run Code Online (Sandbox Code Playgroud)
在我们的XIB中添加UILabel时,我们现在可以选择类型为UILabelHeadingBold的类,并且它按预期工作.标签显示正确的字体和颜色,如我们的AppDelegate中所指定.
但是,如果我们以编程方式创建标签,例如.
UILabelHeadingBold *headingLabel = [[UILabelHeadingBold alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
[self.mainView addSubview:headingLabel];
Run Code Online (Sandbox Code Playgroud)
UILabel没有应用预期的字体/颜色.我们必须手动应用这些属性.
有没有办法让UIAppearance在编程创建的UI元素上生效,还是仅在XIB中使用时才有效?
Mox*_*oxy 19
来自Apple文档:
为了支持外观定制,类必须符合UIAppearanceContainer协议和相关的访问方法必须注明UI_APPEARANCE_SELECTOR.
例如UINavigationBar.h,tintColor中标有UI_APPEARANCE_SELECTOR
@property(nonatomic,retain) UIColor *tintColor UI_APPEARANCE_SELECTOR;
Run Code Online (Sandbox Code Playgroud)
但是在UILabel.h中你可以看到textColor和font属性没有用UI_APPEARANCE_SELECTOR标记,但是当它在Interface Builder中添加时它会起作用(遵循文档它根本不起作用).
Rob*_*jas 14
对我没有任何问题的简单hack是创建一个带有UIAppearance setter的类,它可以修改UILabel属性.
遵循UIAppearance约定我创建了一个方法:
- (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);
}
}
Run Code Online (Sandbox Code Playgroud)
在UILabel类别中:
@interface UILabel (UISS)
- (void)setTextAttributes:(NSDictionary *)numberTextAttributes UI_APPEARANCE_SELECTOR;
@end
Run Code Online (Sandbox Code Playgroud)
我还在试图弄清楚为什么原来的setter不起作用.
我遇到了完全相同的问题,但是在Swift中。UILabel如果从情节提要中添加了自定义外观,则可以使用,但是从代码中添加时则无效。
这是我在Swift中找到的对我有用的解决方案:
class MyLabel: UILabel { }
extension UILabel {
@objc dynamic var customFont: UIFont! {
get { return self.font }
set { self.font = newValue }
}
@objc dynamic var customColor: UIColor! {
get { return self.textColor }
set { self.textColor = newValue }
}
}
Run Code Online (Sandbox Code Playgroud)
然后在配置应用程序外观的位置添加以下行:
MyLabel.appearance().customFont = UIFont.systemFont(ofSize: 20)
MyLabel.appearance().customColor = UIColor.magenta
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4523 次 |
| 最近记录: |