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;
相关推荐
壹方秘境40 分钟前
厌倦了那些看着像一个模版复刻出来的抓包工具,我开发了一款iOS端HTTPS抓包调试工具
ios·程序员·产品
开心就好20255 小时前
不同阶段的 iOS 应用混淆工具怎么组合使用,源码混淆、IPA混淆
后端·ios
世界不及妳微笑5 小时前
关于Xcode26.4 踩坑适配
ios·xcode
iceiceiceice5 小时前
iOS 26 适配 | 使用 `hidesSharedBackground` 保持导航栏按钮原有样式
ios·objective-c·编程语言
SY.ZHOU8 小时前
移动端架构体系(一):组件化
android·ios·架构·系统架构
人月神话Lee14 小时前
一个iOS开发者对Flutter中Widget、Element和RenderObject的理解
前端·flutter·ios
2501_9160074714 小时前
iOS 开发工具有哪些 按开发流程整理的工具清单
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
2501_9159214314 小时前
2026 iOS 上架新趋势 iOS 发布流程模块化
android·ios·小程序·https·uni-app·iphone·webview
库奇噜啦呼15 小时前
【iOS】Effective Objective-C第四章
ios·objective-c·cocoa