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;
相关推荐
sweet丶4 小时前
iOS AI 编程环境配置:Agent、Skill、Rules、Hook、Command
ios·ai编程
2501_915909064 小时前
iOS应用性能优化:十大策略提升用户体验与开发效率
android·ios·小程序·https·uni-app·iphone·webview
白玉cfc8 小时前
【iOS】底层原理:分类、扩展和关联对象
ios·分类·数据挖掘
2601_955767429 小时前
观复盾护景贴:东方哲思与双护科技的深度实测
人工智能·科技·ios·iphone·圆偏振光·磁控溅射
会Tk矩阵群控的小木9 小时前
企业级iMessage群发系统实战:单主机管控多iPhone设备完整实现
运维·ios·开源软件·个人开发
人月神话-Lee10 小时前
【图像处理】vImage/Accelerate——SIMD 让 CPU 也能飞
图像处理·深度学习·ios·cnn·ai编程·swift
万能小林子10 小时前
如何将网页在线转APP?5种打包工具对比速成指南(含在线/手机/电脑方案)
android·ios·uni-app·web app·wap2app·app打包·app封装
2601_9557674211 小时前
iPhone 17屏幕反光怎么解?磁控溅射AR膜实测反射率低至0.5%
ios·ar·iphone·#观复盾护景贴·scinique双护技术
盼小辉丶12 小时前
PyTorch深度学习实战(56)——在iOS上构建PyTorch应用
pytorch·深度学习·ios
for_ever_love__21 小时前
UI学习:UISearchController基础了解和应用
学习·ui·ios·objective-c