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;
相关推荐
kevinli2 天前
available没你想象中的可靠
ios·编译原理
CodeJourney_J3 天前
如何通过SMB协议实现手机共享电脑文件
windows·ios·smb
ipad协议开发3 天前
企业微信iPad协议接口深度解析:技术原理、应用场景与开发实战
ios·企业微信·ipad
千里马-horse3 天前
Building a Simple Engine -- Mobile Development -- Platform considerations
android·ios·rendering·vulkan
systeminof4 天前
全新MacBook发布:苹果公司将 iPhone 芯片带入笔记本时代
ios·iphone
pop_xiaoli4 天前
effective-Objective-C 第四章阅读笔记
笔记·ios·objective-c·cocoa·xcode
前端不太难4 天前
Flutter 适合什么团队?RN / iOS 各自的边界在哪?
flutter·ios
带娃的IT创业者5 天前
解密OpenClaw系列10-OpenClaw系统要求
人工智能·macos·ios·objective-c·ai智能体·智能体开发·openclaw