You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NSMutableParagraphStyle导致表情符号显示异常问题

解决UILabel设置行高后表情符号显示异常的问题

这个问题的核心坑点在于你计算NSRange时用了self.count——Swift里String.count统计的是视觉上的Unicode字符数(比如一个表情算1个),但NSRange是基于Objective-C框架的类型,它需要的是UTF-16编码单元的长度。像😀这类表情属于UTF-16代理对,会占用2个编码单元,直接用self.count会导致range长度计算错误,富文本样式没法覆盖整个字符串,最终引发表情显示异常。

修正后的String扩展代码

把range的长度计算换成基于utf16.count的方式即可:

extension String {
    func addLineHeightWith(alignment: NSTextAlignment) -> NSAttributedString {
        let attrString = NSMutableAttributedString(string: self)
        let style = NSMutableParagraphStyle()
        style.lineSpacing = 5
        style.minimumLineHeight = 5
        style.alignment = alignment
        // 关键修正:用utf16.count获取UTF-16编码单元的真实长度
        let range = NSRange(location: 0, length: self.utf16.count)
        attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: range)
        return attrString
    }
}

补充说明

顺便提一句,建议把方法名里的alignement拼写修正为alignment(符合英文拼写规范),避免后续维护时的混淆。

内容的提问来源于stack exchange,提问作者Florian Ldt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:50:52