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;
相关推荐
开心就好202541 分钟前
通配符 Bundle ID 和精确 Bundle ID 怎么选,推送、iCloud 能不能用通配符
后端·ios
布莱克6055 小时前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
茶底世界之下5 小时前
冬日窗边的早餐:用 Awaking 留住冷光里的暖意
ios·app·产品
布莱克6056 小时前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包
茶底世界之下1 天前
雨后的黄电车:用 Awaking 给灰色街景定一个主角
ios·app·产品
恋猫de小郭1 天前
iOS for Web ,把原生 iOS App 跑到进浏览器里面,倒反天罡
android·前端·ios
00后程序员2 天前
iOS 实时活动怎么开发,Windows 上用 KXBuild 和 ActivityKit 写灵动岛
后端·ios
iReaShare2 天前
如何在没有 Wi-Fi 的情况下备份 iPhone
ios
CocoaKier3 天前
苹果开发者注意,请在2027年1月31日前完成合规验证,否则中国区可能下架
ios·aigc·apple
二流小码农3 天前
鸿蒙开发:证书只能创建3个,第4个应用怎么办
android·ios·harmonyos