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;
相关推荐
SY.ZHOU14 小时前
大型工程跨全平台实践总结
flutter·ios·安卓·鸿蒙
denggun1234517 小时前
Sendable 协议-Swift 结构化并发的核心安全保障
ios·swift
奶糖的次元空间18 小时前
iOS 学习笔记 - 创建第一个APP
ios
for_ever_love__18 小时前
Objective-C 学习 NSString 和 NSMutableString的基本功能详解
学习·ios·objective-c
@大迁世界20 小时前
注意,苹果刚刚做出改变: iOS 26.4 系统强制所有设备开启“被盗设备保护”功能。
macos·ios·objective-c·cocoa
卢锡荣1 天前
LDR6021Q 车规级 Type‑C PD 控制芯片:一芯赋能,边充边传,稳驭全场景
c语言·开发语言·ios·计算机外设·电脑
2501_907136821 天前
iOS任意版本号APP下载
ios·软件需求
denggun123452 天前
结构化并发(Structured Concurrency)
开发语言·ios·swift
weixin_403810132 天前
EasyClick iOS USB版本蓝牙点击坐标代码
ios·自动化·代理模式
良逍Ai出海2 天前
Xcode 26来AI了:iOS独立开发者3步接入实测
人工智能·ios·xcode