【发布时间】:2021-02-10 18:07:50
【问题描述】:
从API 接收HTML 输入String。
将HTML 转换为NSAttributeString --> Unicode 面临空白空间问题 - \u200b
如何从HTML 到NSAttributeString 删除这个空白?
API 响应:
{
"message" : "[<b>1-</b> Fill\U200b t\U200bhe \U200b\U200b\U200bBreak Do\U200bwn Table]"
}
结构 - 解码器:
{
"message" : "[<b>1-</b> Fill the Break Down Table]"
}
UILabel 文本:
labet.text = Message.message // [<b>1-</b> Fill the Break Down Table] - SHOWING IN UI
UILabel 属性文本:
labet.attributedText = Message.message.htmlAttributedString()
属性输出:
分机代码:
func htmlAttributedString() -> NSMutableAttributedString {
guard let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
else { return NSMutableAttributedString() }
guard let formattedString = try? NSMutableAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil )
else { return NSMutableAttributedString() }
return formattedString
}
有人可以指导我吗?如何避免这个空间?
【问题讨论】:
-
只需使用replacingOccurrences将unicode空格替换为空白字符串即可。
-
\U200b是用于零宽度空间的 unicode。我不确定为什么它会在你的 UI 中显示为实际空间,我也不确定为什么这些字符会出现。正如其他人建议的那样,把它们去掉。 -
是的。这是我的疑问。在属性文本“\u{200B}”中 - 出现空格,在 label.text 中“\u{200B}” - 没有出现空格
-
@DuncanC 你知道这背后的概念吗?
-
.characterEncoding需要有一个NSNumber值。
标签: ios swift unicode uilabel nsattributedstring