// 设置颜色根据范围
- (void)addColor:(UIColor *)color location:(NSInteger)location length:(NSInteger)length
{
NSMutableAttributedString *attStr = [self.attributedText mutableCopy];
if (location != NSNotFound) {
[attStr addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(location, length)];
}
self.attributedText = attStr;
}
// 设置字体根据范围
- (void)addFont:(CGFloat)size location:(NSInteger)location length:(NSInteger)length
{
NSMutableAttributedString *attStr = [self.attributedText mutableCopy];
if (location != NSNotFound) {
[attStr addAttribute:NSFontAttributeName value:FontWithWidth(size) range:NSMakeRange(location, length)];
}
self.attributedText = attStr;
}
// 设置行间距
- (void)addParagraphStyle:(CGFloat)size
{
NSMutableAttributedString *attStr = [self.attributedText mutableCopy];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:size];
[attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.text.length)];
self.attributedText = attStr;
}
给UILabel扩展以上方法就可以了,如有bug欢迎联系,会修复。
本文提供了一种方法,用于为UILabel添加颜色、字体和行间距属性,通过修改范围来实现局部样式调整。代码示例清晰易懂,适合开发者快速上手。

890

被折叠的 条评论
为什么被折叠?



