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;
相关推荐
布莱克6051 天前
Swift 类详解:从定义、继承到内存管理的完整指南
服务器·开发语言·ios·ssh·swift·类
布莱克6051 天前
Swift 方法详解:实例方法、类型方法与 mutating 机制
服务器·开发语言·ios·ssh·swift·方法
茶底世界之下2 天前
旧电影院的红座椅:用 Awaking 留住放映前的光
ios·app·产品
茶底世界之下2 天前
洗衣房的午后斜光:用 Awaking 把光和影分开
ios·app·产品
我是谁的程序员3 天前
iOS 性能分析在 Windows 上怎么做,用 KXBuild 的 kxdevice 替代 Instruments
后端·ios
开心就好20253 天前
通配符 Bundle ID 和精确 Bundle ID 怎么选,推送、iCloud 能不能用通配符
后端·ios
布莱克6053 天前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
茶底世界之下3 天前
冬日窗边的早餐:用 Awaking 留住冷光里的暖意
ios·app·产品
布莱克6053 天前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包
茶底世界之下5 天前
雨后的黄电车:用 Awaking 给灰色街景定一个主角
ios·app·产品