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;
相关推荐
Digitally14 小时前
如何在不使用iTunes的情况下在电脑上访问iPhone文件
ios·电脑·iphone
QuantumLeap丶14 小时前
《Flutter全栈开发实战指南:从零到高级》- 14 -网络请求与数据解析
flutter·ios·dart
RollingPin14 小时前
iOS 内存管理之 autoreleasePool
ios·内存管理·runtime·autoreleasepool
2501_9159214317 小时前
查看iOS App实时日志的正确方式,多工具协同打造高效调试与问题定位体系(2025最新指南)
android·ios·小程序·https·uni-app·iphone·webview
ajassi200020 小时前
开源 Objective-C IOS 应用开发(四)Xcode工程文件结构
ios·开源·objective-c
G佳伟21 小时前
如何解决解决,微信小程序ios无法长按复制问题<text>设置 selectable=“true“不起作用
ios·微信小程序·小程序
Nick568321 小时前
Apple Pay 与 Google Pay 开发与结算全流程文档
ios·安卓·android-studio
全栈派森21 小时前
初见 Dart:这门新语言如何让你的 App「动」起来?
android·flutter·ios
HarderCoder21 小时前
Swift 内存管理:吃透 ARC 、weak、unowned
ios·swift
Digitally1 天前
5种将照片从iPhone传输到戴尔PC/笔记本电脑的方法
ios·电脑·iphone