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;
相关推荐
00后程序员张2 小时前
苹果App Store上架指南:费用、原理与步骤详解
android·ios·小程序·https·uni-app·iphone·webview
黑科技iOS上架2 小时前
Unity3D游戏过审App Store4.3机审实战
ios·审核·ios混淆·执行程序差异化
用户38034165882974 小时前
控制中心一键后台录音:我被自己的 Spike 骗了两次
ios·swift
Crazy_MT4 小时前
App 可能不再是入口:从 iOS 27 快捷指令看苹果的 AI Agent 野心
人工智能·ios·apple
Maple9964 小时前
Firebase iOS SDK 重大事故:一个 nil key 如何让全球 App 集体崩溃
ios
鹤卿1238 小时前
「iOS」GCD
开发语言·ios·objective-c
黑科技iOS上架8 小时前
小蟹iOS编译级混淆与定向加固配合使用完整教程
ios·审核·ios混淆·执行程序差异化
传奇开心果编程8 小时前
【Flutter入门练中学】第3课:滚动与列表
android·学习·flutter·ui·ios
for_ever_love__8 小时前
iOS: CABasicAnimation动画
macos·ios·cocoa
天神哥哥啊9 小时前
unity联调注意事项-IOS
unity·ios·游戏引擎