【问题标题】:Swift - Convert HTML text to Attributed StringSwift - 将 HTML 文本转换为属性字符串
【发布时间】:2018-05-24 10:23:59
【问题描述】:

在我的一个模块中,我想使用 UILabel 将多语言 HTML 文本(英语和泰米尔语)显示为 NSAttributedString。如果文本是纯英文,我可以将其作为我的愿望Using this way。但我的内容包含英语和泰米尔语字符。我怎么能处理这种情况。如果有人知道,请分享您的建议。

HTML 内容

<medium><b><font color='#2f3744'>IPL Tamil Web Series Episode #3 | யாருடா Swetha ? | Tamil Comedy Web Series | Being Thamizhan</font></b></medium> has been succesfully scheduled on <medium><b><font color='#2f3744'>2018-05-23 08:51 PM</font></b></medium>

期待

IPL 泰米尔语网络系列第 3 集 | யாருடா Swetha ? |泰米尔喜剧网络系列 |成为Thamizhan已成功安排在2018-05-23 08:45 PM

电流输出

IPL 泰米尔语网络系列第 3 集 | &*$%!@#$@^&$&^%$ 斯韦莎? |泰米尔喜剧网络系列 |成为Thamizhan已成功安排在2018-05-23 08:45 PM

注意:我尝试使用下面的代码 sn-p 来存档

extension String {
var htmlToAttributedString: NSAttributedString? {
    guard let data = data(using: .utf8) else { return NSAttributedString() }
    do {
        return try NSAttributedString(data: data, options:
            [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
    } catch {
        return NSAttributedString()
    }
}
var htmlToString: String {
    return htmlToAttributedString?.string ?? ""
}
}

【问题讨论】:

标签: html ios swift nsattributedstring


【解决方案1】:

我用你的 html 尝试了这个解决方案,效果很好:

let htmlText = "<medium><b><font color='#2f3744'>IPL Tamil Web Series Episode #3 | யாருடா Swetha ? | Tamil Comedy Web Series | Being Thamizhan</font></b></medium> has been succesfully scheduled on <medium><b><font color='#2f3744'>2018-05-23 08:51 PM</font></b></medium>"
let encodedData = htmlText.data(using: String.Encoding.utf8)!
var attributedString: NSAttributedString

do {
    attributedString = try NSAttributedString(data: encodedData, options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding:NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)
} catch let error as NSError {
    print(error.localizedDescription)
} catch {
    print("error")
}

attributedString 输出:

IPL 泰米尔语网络系列第 3 集 | யாருடா Swetha ? |泰米尔喜剧网络系列 |成为Thamizhan已成功安排在2018-05-23 08:45 PM

【讨论】:

  • 太棒了!工作正常。谢谢兄弟。
  • 图片加载问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多