NSAttributedString设置折行方式NSLineBreakByTruncatingTail,计算高度出错,高度返回异常。

iOS13上,NSAttributedString设置折行方式NSLineBreakByTruncatingTail,计算高度出错,只返回一行的高度。

NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];

style.hyphenationFactor = 1; // 设置每行的最后单词是否截断,在0.0-1.0之间,默认为0.0,越接近1.0单词被截断的可能性越大,

设置hyphenationFactor=1,在计算就返回正常高度了。

如果设置不起效。换下面的方法

找到了解决方案。只需将 NSMutableParagraphStyle 上的 setAllowsDefaultTighteningForTruncation 设置为 YES。

参考 cocoa - Making NSTextField not shrink when NSLineBreakByTruncatingTail is set - Stack Overflow

复制代码
    NSString *highlightTitle = title;

    //转换参数

    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };

    //将html文本转换为正常格式的文本

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[highlightTitle dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];

    

    [attributedString removeAttribute:NSParagraphStyleAttributeName range: NSMakeRange(0, attributedString.length)];

    [attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedString.length)];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

//    paragraphStyle.hyphenationFactor = 1;

    [paragraphStyle setLineSpacing:space];

    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;

    [paragraphStyle setAllowsDefaultTighteningForTruncation:YES];

    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];

    return attributedString;
相关推荐
linweidong23 分钟前
网易ios面试题及参考答案(上)
ios·cdn·进程状态·虚拟内存·raii·网络链路·dns系统
從南走到北20 小时前
JAVA海外短剧国际版源码支持H5+Android+IOS
android·java·ios
疯笔码良21 小时前
iOS 国际化与本地化完整指南
ios·swift
库奇噜啦呼1 天前
【iOS】GCD学习
学习·ios·cocoa
Kathleen1001 天前
iOS--TableView的复用机制以及性能优化(处理网络数据)
ios·性能优化·网络请求·gcd·uitableview
子春一1 天前
Flutter 与原生平台深度集成:打通 iOS 与 Android 的最后一公里
android·flutter·ios
依旧风轻1 天前
objc_object 与 objc_class 是一定要了解的底层结构
ios·objective-c·isa·objc_class·objc_object