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

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

NSMutableParagraphStyle *style = \[NSMutableParagraphStyle allocinit];

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;
相关推荐
黑科技iOS上架16 小时前
iOS4.3合规自测手段:二进制分析
flutter·ios·cocoa·审核
网易易盾2 天前
iOS 设备环境核验接入实践:从特征扫描到运行时完整性识别
ios
布莱克6052 天前
Swift 自动引用计数(ARC)详解:原理、循环引用与最佳实践
开发语言·ios·swift·arc·自动引用计数
软件交付观察室3 天前
用户关掉手机定位权限后,原生App还能显示哪些位置?
android·ios·移动开发
KevinWang_4 天前
iOS 开发计划(一) - 通过 Scriptable app 在 iOS 上运行 JavaScript 脚本
javascript·ios
布莱克6055 天前
Swift 下标(Subscript)详解:从语法到实战
服务器·开发语言·ios·ssh·swift·下标
茶底世界之下5 天前
雨天的窗边:用 Awaking 轻轻提亮一盆蕨
ios·app·产品
景彬6 天前
强制升级 Xcode 后,一个 10 年老项目有哪些改动点
ios
茶底世界之下7 天前
海边书店的阴天:用 Awaking 留住青绿与暖灯
ios·app·产品
布莱克6057 天前
Swift 类详解:从定义、继承到内存管理的完整指南
服务器·开发语言·ios·ssh·swift·类