繼承UILabel寫個(gè)類,快速設(shè)置多種字體屬性毡代。
思路
把Label顯示的內(nèi)容中阅羹,屬性相同的連續(xù)文字作為一個(gè)段(Section),這樣只需要對(duì)外提供兩個(gè)方法教寂,即可實(shí)現(xiàn)捏鱼。
- 為指定的段設(shè)置屬性
- 為指定的段設(shè)置文字
類定義
JXAttributeLabel.h
@interface JXAttributeLabel : UILabel
/// 設(shè)置屬性,section為段號(hào)
- (void)setAttributes:(NSDictionary *)attributes atSection:(NSInteger)section;
/// 設(shè)置字符串酪耕,section為段號(hào)
- (void)setString:(NSString *)string atSection:(NSInteger)section;
@end
調(diào)用方法
我做了個(gè)Demo导梆,在一個(gè)Label上展示四段屬性隨機(jī)的文字。
- (IBAction)touchSection0:(UIButton *)sender {
[self setRandomContentWithSectionIndex:0];
}
- (IBAction)touchSection1:(UIButton *)sender {
[self setRandomContentWithSectionIndex:1];
}
- (IBAction)touchSection2:(UIButton *)sender {
[self setRandomContentWithSectionIndex:2];
}
- (IBAction)touchSection3:(UIButton *)sender {
[self setRandomContentWithSectionIndex:3];
}
- (void)setRandomContentWithSectionIndex:(NSInteger)sectionIndex {
NSDictionary *attr = [self randomAttribute];
NSString *str = [self randomString];
[self.label setAttributes:attr atSection:sectionIndex];
[self.label setString:str atSection:sectionIndex];
}
- (NSDictionary *)randomAttribute {
NSInteger fontSize = arc4random_uniform(6) + 12;
UIFont *font = [UIFont systemFontOfSize:fontSize];
UIColor *color = [UIColor colorWithRed:arc4random_uniform(255) / 255.0 green:arc4random_uniform(255) / 255.0 blue:arc4random_uniform(255) / 255.0 alpha:1.0];
return @{NSFontAttributeName : font,
NSForegroundColorAttributeName : color};
}
- (NSString *)randomString {
NSInteger index = arc4random_uniform(4);
return self.stringArray[index];
}
可以看到因妇,使用方法就是兩行:
[self.label setAttributes:attr atSection:sectionIndex];
[self.label setString:str atSection:sectionIndex];