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;
相关推荐
YJlio5 小时前
1.7 通过 Sysinternals Live 在线运行工具:不下载也能用的“云端工具箱”
c语言·网络·python·数码相机·ios·django·iphone
2501_9419820515 小时前
Go 开发实战:基于 RPA 接口的主动消息推送
ios·iphone
忆江南16 小时前
Swift 全面深入指南
ios
00后程序员张18 小时前
iOS 应用代码混淆,对已编译 IPA 进行类与方法混淆
android·ios·小程序·https·uni-app·iphone·webview
YJlio19 小时前
1.6 使用 Streams 工具移除下载文件的 ADS 信息:把“来自互联网”的小尾巴剪掉
c语言·网络·python·数码相机·ios·django·iphone
阿捏利19 小时前
详解Mach-O(五)Mach-O LC_SYMTAB
macos·ios·c/c++·mach-o
文件夹__iOS20 小时前
Swift 性能优化:Copy-on-Write(COW) 与懒加载核心技巧
开发语言·ios·swift
Sheffi6620 小时前
Xcode 26.3 AI编程搭档深度解析:如何用自然语言10分钟开发完整iOS应用
ios·ai编程·xcode
符哥200820 小时前
使用Apollo和GraphQL搭建一套网络框架
ios·swift·rxswift
2601_9491465320 小时前
Swift语音通知接口集成手册:iOS/macOS开发者如何调用语音API
macos·ios·swift