简单易用的封装:在一个Label上显示多种字体属性

继承UILabel写个类,快速设置多种字体属性。

JXAttributeLabel.png

思路

把Label显示的内容中,属性相同的连续文字作为一个段(Section),这样只需要对外提供两个方法,即可实现。

  • 为指定的段设置属性
  • 为指定的段设置文字

类定义

JXAttributeLabel.h

@interface JXAttributeLabel : UILabel

/// 设置属性,section为段号
- (void)setAttributes:(NSDictionary *)attributes atSection:(NSInteger)section;

/// 设置字符串,section为段号
- (void)setString:(NSString *)string atSection:(NSInteger)section;

@end

调用方法

我做了个Demo,在一个Label上展示四段属性随机的文字。

JXAttributeLabel.gif
- (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];

项目源码

JXAttributeLabel

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,261评论 4 61
  • 01 大学毕业以后,我选择回到家乡。 那是南方的一座小县城,而我的家,是在距离县城17公里的一个小村落里。 我是村...
    吴廿九阅读 267评论 0 0
  • 范雨素的一篇自述,因话语质朴、感情真挚、故事写实,给现实壁垒里的赶路人带去一些坚定。作为资深的“老北漂”,回顾过去...
    姬鲲阅读 207评论 0 2
  • 永华用墨娱百乐,风涛入笔成画图 ——专访浙江省书法艺术家刘永华先生 全媒体记者:张行方 刘永华先生,字同鑫,号妙生...
    70ad1bea2306阅读 842评论 0 2