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;
相关推荐
疯华整猫6 小时前
别再抄 Flutter 了:2026 年 Android / iOS / 小程序跨端架构选型的四本成本账
android·前端·ios
黑科技iOS上架6 小时前
iOS游戏换皮上架困境:4.3同质化拒审
人工智能·ios·审核
黑科技iOS上架6 小时前
iOS二次开发应用上架难题:4.3a同质化拒审
ios·审核
传奇开心果编程6 小时前
【Flutter踩坑排雷】第30课:异常未捕获坑|未捕获异常直接闪退,全局兜底故障处理
android·flutter·ios·移动开发·dart·ui框架·声明式ui
茶底世界之下7 小时前
海边游乐场的黄昏:用 Awaking 留住一层暖光
ios·app·产品
90后的晨仔19 小时前
Xcode 27.1 下,老工程如何在 iPhone Duo 模拟器上跑起来
ios
90后的晨仔20 小时前
Xcode 27 升级后满屏 deployment target 报错?一文搞定
ios
二流小码农1 天前
鸿蒙开发:router组件升级,彻底告别手动配置
android·ios·harmonyos
茶底世界之下1 天前
雾中山路的冷光层次:用 Awaking 留住红色背影
ios·app·产品
Digitally1 天前
iPhone 如何添加日历?
ios·iphone