富文本显示异常

引用:富文本首行缩进引起的换行异常

最近开发遇到一个问题,命名UILabel设置了lineBreakMode的显示模式,但是最终就是没效果!!!WTF?(富文本末尾的省略号不见了。。。)

后来找到原因了,label显示的富文本限制了行数并且添加了段落样式,此时lineBreakMode就会失效

解决方案:

加上下面这一行即可

[paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];

最终的代码如下:

NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];

NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:6];
[paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.contentLabel.text length])];
[self.contentLabel setAttributedText:attributedString];

可以正常显示末尾的省略号!!!

我这里提供一个创建富文本属性字典的快捷方法,可以方便创建富文本字符串,仅供参考

新建一个工具类,将下面代码写到里面,外层直接传参调用

+ (NSDictionary *)getAttributeDictWithLineBreakMode:(NSLineBreakMode)lineBreakMode
                               withAlignment:(NSTextAlignment)alignment
                                    withFont:(UIFont *)font
                               withLineSpace:(CGFloat)lineSpace
                         withWordSpace:(NSNumber *)wordSpace
                        andParagraphSpaceing:(CGFloat)paragraphSpacing {

    // 1. 创建样式对象
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    // 2. 段落格式
    style.lineBreakMode = lineBreakMode;
    // 3. 对齐方式
    style.alignment = alignment;
    // 4. 设置行间距
    style.lineSpacing = lineSpace;
    // 5. 连字符号链接
    style.hyphenationFactor = 1.0f;
    // 6. 首行缩进
    style.firstLineHeadIndent = 0.f;
    // 7. 段间距
    style.paragraphSpacing = paragraphSpacing;
    // 8. 段前间距
    style.paragraphSpacingBefore = 0.0f;
    // 9. 除首行之外其他行缩进
    style.headIndent = 0.0f;
    // 10. 每行容纳字符的宽度
    style.tailIndent = 0.0f;
    
    NSDictionary *dict = @{
        NSFontAttributeName : font,
        NSParagraphStyleAttributeName : style,
        NSKernAttributeName : wordSpace,
    };
    return dict;
}

如下调用

NSDictionary *attributeDict = [UPTextTool getAttributeDictWithLineBreakMode:NSLineBreakByTruncatingTail withAlignment:NSTextAlignmentLeft withFont:[UIFont systemFontOfSize:16.f] withLineSpace:5.f withWordSpace:@(1.f) andParagraphSpaceing:1.f];
        
NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc] initWithString:@"要显示的文本" attributes:attributeDict];

你可能感兴趣的:(富文本显示异常)