你是如何创建常用的属性文本?
2018-12-10 本文已影响3人
arnoldxiao
假设我们定义了一个 UILabel 对象,它的 frame 属性在初始化的时候就给定了,前提是有足够大的宽高显示其内容,设置其内容可换行显示。
把 UILabel 对象加入到视图中,并给其赋值。
1. 直接使用系统API——NSMutableAttributedString
self.textLabel.attributedText = ({
NSString *prefix = @"我是";
NSString *middle = @"张三";
NSString *suffix = @"不是李四";
NSString *introduce = [[[prefix stringByAppendingString:middle] stringByAppendingString:@"\n"] stringByAppendingString:suffix];
NSRange prefixRange = [introduce rangeOfString:prefix];
NSRange middleRange = [introduce rangeOfString:middle];
NSRange suffixRange = [introduce rangeOfString:suffix];
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:introduce];
[mutableAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:prefixRange];
[mutableAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:middleRange];
[mutableAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:suffixRange];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:prefixRange];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:middleRange];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:UIColor.lightGrayColor range:suffixRange];
mutableAttributedString;
});
我们可以直接运行代码看效果如何:
NSMutableAttributedString-UI.png
效果在我们预想中的那样,但是这样的代码有哪些不好的地方呢?
-
代码量大,这只是一个很简单的属性文本,如果稍微复杂点,代码量更是很难控制;
-
阅读不便,多次调用
addAttribute: value: range:,使代码阅读者眼花缭乱; -
NSRange的使用容易出错,如果文本中存在重复内容的文本,指定其NSRange的时候尤其要注意;
2. 使用AXAttributedString
这是我使用原生NSAttributedString封装的一个代码,采用类似 Masonry 链式语法,代码简单,阅读方便,下面贴代码:
self.textLabel.attributedText = [AXAttributedString makeAttributedString:^(AXAttributedStringMaker *make) {
make.text(@"我不是").systemFontSize(14).foregroundColor([UIColor grayColor]);
make.text(@"李四").foregroundColor(UIColorFromRGB(0xFF0000)).font([UIFont systemFontOfSize:30]);
make.text(@"\n");
make.text(@"不是王老五").systemFontSize(12).foregroundColor(UIColor.lightGrayColor);
}];
来看看效果如何:
AXAttributedString-UI.png
和直接使用NSMutableAttributedString相比,最直接的变化就是取消了NSRange的参与,这个在属性文本中最容易出Bug的地方。
当然,以上是基于静态文本的例子~
如果大家有兴趣,可以学习使用这个代码~
地址:https://github.com/arnoldxiao/AXAttributedString
欢迎大家给我提建议,如果喜欢,给我个star最好啦~