目前,我所有的按钮和文本字段均具有attributedText
值,这些值定义为属性字符串。
考虑简单的UILabel
的情况。每当我必须更改此UILabel
的文本(基于某些用户操作)时,都必须重新定义NSAttributedString
上的属性。一种方法是简单地创建一个子例程,该例程在我需要它们时会生成这些属性,但是考虑到可能存在许多需要这种便捷方法的不同标签(或属性字符串),这是一个问题。
另一个可能是简单地更改text
字段,并让观察者添加这些属性,但这工作量相同,现在可能会更加复杂。
是否有一种简单的方法可以实现上述目的而无需重新定义属性?
最佳答案
探索@Harry的想法,这里有一些想法:NSAttributedString
上的类别,UILabel
上的类别或NSDictionary
上的类别,可能是它们的组合,根据哪种最适合您和您的项目。
如果要对其他类型的对象(如NSAttributedString
)使用自定义UILabel
,则在NSAttributedString
之前优先使用UITextView
上的类别可能会更有趣。
一个好的开始:
typedef enum : NSUInteger {
AttributeStyle1,
AttributeStyle2,
} AttributeStyles;
NSDictionary
上可能的分类方法:-(NSDictionary *)attributesForStyle:(AttributeStyles)style
{
NSDictionary *attributes;
switch(style)
{
case AttributeStyle1:
attributes = @{}//Set it
break;
case AttributeStyle2:
attributes = @{}//Set it
break;
default:
attributes = @{}//Set it
break;
}
return attributes;
}
UILabel
上可能的类别:-(void)setString:(NSString *)string withAttributes:(NSDictionary *)attributes
{
[self setAttributedText:[[NSAttributedString alloc] initWithString:string attributes:attributes];
}
NSAttributedString
上可能的类别:-(NSAttributedString *)initWithString:(NSString *)string withStyle:(AttributedStyles)style
{
//Here, a mix is possible using the first method, or doing here the switch case
//Ex: return [[NSAttributedString alloc] initWithString:string attributes:[NSDictionary attributesForStyle:style];
//And to use like this: [yourLabel setAttributedText:[[NSAttributedString alloc] initWithString:string withStyle:AttributeStyle1];
}