Swift:在将 html 字符串转换为属性字符串时添加空格

问题描述

HTML 接收 String 类型 API

HTML 转换为 NSAttributeString --> Unicode - \u200b 面临空空间问题

如何去除 HTMLNSAttributeString间的空白?

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() 

属性输出

attribute_output

- SHOWING IN UI

扩展代码

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
}

有人可以指导我吗?如何避开这个空间?

解决方法

试试这个:

labet.attributedText = Message.message.replacingOccurrences(of: "\u{200B}",with: "").htmlAttributedString()