【问题标题】:Swift: Empty space adding while converting html string to attribute stringSwift:将html字符串转换为属性字符串时添加空格
【发布时间】:2021-02-10 18:07:50
【问题描述】:

API 接收HTML 输入String

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

属性输出:

- 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
}

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

【问题讨论】:

  • 只需使用replacingOccurrences将unicode空格替换为空白字符串即可。
  • \U200b 是用于零宽度空间的 unicode。我不确定为什么它会在你的 UI 中显示为实际空间,我也不确定为什么这些字符会出现。正如其他人建议的那样,把它们去掉。
  • 是的。这是我的疑问。在属性文本“\u{200B}”中 - 出现空格,在 label.text 中“\u{200B}” - 没有出现空格
  • @DuncanC 你知道这背后的概念吗?
  • .characterEncoding 需要有一个 NSNumber 值。

标签: ios swift unicode uilabel nsattributedstring


【解决方案1】:

试试这个:

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

【讨论】:

  • 是的。它正在工作。之前,我认为 swift unicode 语法与 api 响应的 unicode 不同。
  • 为什么不直接过滤?
  • @LeoDabus 刚刚写了我想到的第一个。它也可以是过滤器,我认为它更适合这种情况。
  • @LeoDabus 这是我的疑问。在属性文本“\u{200B}”中 - 出现空格,在 label.text “\u{200B}”中 - 没有出现空格??
  • @McDonal_11 这与标签无关。这是由于属性字符串的DocumentType.html 选项在后台使用WebKit 来呈现html。我认为这就是为什么这个 unicode 被识别的原因。如果您只是尝试使用常规属性字符串,则不会显示空格。
猜你喜欢
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
相关资源
最近更新 更多