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;
相关推荐
少云清18 小时前
IOS历史版本下载
ios
奶糖的次元空间2 天前
iOS 学习笔记 - SwiftUI 和 简单布局
ios·swift
zhensherlock2 天前
Protocol Launcher 系列:App Store 精准引流与应用推广
javascript·macos·ios·typescript·iphone·mac·ipad
for_ever_love__2 天前
Objective-C学习 NSDictionary,NSMutableDictionary 功能详解
开发语言·学习·ios·objective-c
for_ever_love__2 天前
Objective-C学习 协议和委托
开发语言·学习·ios·objective-c
2501_915909063 天前
不用越狱就看不到 iOS App 内部文件?使用 Keymob 查看和导出应用数据目录
android·ios·小程序·https·uni-app·iphone·webview
@大迁世界3 天前
液态玻璃屏正在侵蚀你的电池
macos·ios·objective-c·cocoa
pop_xiaoli3 天前
【iOS】类与对象底层
macos·ios·objective-c·cocoa·xcode
sp42a3 天前
NativeScript iOS 平台开发技巧
ios·nativescript·app 开发
2501_915921433 天前
常用iOS性能测试工具大全及使用指南
android·测试工具·ios·小程序·uni-app·cocoa·iphone