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;
相关推荐
ii_best4 小时前
按键精灵找图脚本怎么写?iOS 找图找色实现与参数要点
人工智能·计算机视觉·ios·自动化·按键精灵
2501_916007476 小时前
Windows 怎么开发 Swift iOS App?SwiftUI 编译与真机调试和打包 ipa
ide·windows·vscode·ios·个人开发·swift·敏捷流程
iOS_MingXing14 小时前
iOS导航栏左上角显示一块白色圆角/圆形
macos·ios·cocoa
ii_best17 小时前
按键精灵和触动精灵哪个好?iOS 自动化选型的四个判断维度
运维·ios·自动化·按键精灵
乐鑫科技 Espressif17 小时前
通过 Wi-Fi Aware 直接将 ESP 设备连接到 iPhone——全新的跨平台 P2P 标准
ios·esp32·iphone·p2p·乐鑫科技
杜哥无敌2 天前
反向代理那些事儿: MaxKB 和1Panel ,用https还是http
ios·iphone
遥不可及zzz2 天前
iOS 27 适配指南:Xcode 27 升级、UIScene 生命周期迁移及游戏项目兼容性处理
ios·ios 27·xcode27
Geek-Chow2 天前
02 · Redux 是什么,又不是什么
ios
楚识科技2 天前
移动端 OCR SDK 集成拆解:Android/iOS 离线识别与结构化回填
android·ios·ocr
CocoaKier2 天前
神技分享:App加锁,App隐藏?苹果官方自带,只需要一个长按
ios·apple