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;
相关推荐
库奇噜啦呼5 小时前
【iOS】Core Data
ios
2501_9151063220 小时前
TraceEagle 代理抓包教程 本机和手机的 HTTPS 抓包方法
网络协议·计算机网络·网络安全·ios·adb·https·udp
云逸_1 天前
Cinder:基于 Swift Macro 与 Mach-O Section 的解耦注册机制
ios·swift
末代iOS程序员华仔1 天前
从 Figma 到上架:使用 Codex 与 MCP 全流程实现 AI 聊天 App
flutter·ios·swift
极客猴子1 天前
苹果手机怎么快速总结长文本?iOS录音APP实测对比
ios·智能手机
一牛1 天前
Swift 循环引用
macos·ios
迷雾悠悠2 天前
企业微信iPad协议聚合聊天系统:从原理到实战开发指南
ios·企业微信·ipad
LDyun_2 天前
.2026主流云手机测评,8款机型高压挂机实测
ios·智能手机·安卓·玩游戏
pop_xiaoli2 天前
【iOS】YYModel源码学习
学习·ios·objective-c·cocoa
霍霍哈嗨2 天前
swiftUI框架基础
ios·swiftui·swift