在我的一个模块中,我想使用 UILabel 将多语言 HTML 文本(英语和泰米尔语)显示为 NSAttributedString。如果文本是纯英文的,我可以按照我的意愿显示它Using this way .但是我的内容包含英语和泰米尔语字符。我该如何处理这种情况。请分享您的建议,如果有人知道的话。
HTML Content
<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>
Expectation
IPL 泰米尔语网络系列第 3 集 | யாருடாSwetha? |泰米尔喜剧网络系列 | Being Thamizhan已成功安排在2018-05-23 08:45 PM
Current Output
IPL 泰米尔语网络系列第 3 集 | &*$%!@#$@^&$&^%$ Swetha? |泰米尔喜剧网络系列 | Being Thamizhan已成功安排在2018-05-23 08:45 PM
注意:我尝试使用下面的代码片段来存档
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 尝试了这个解决方案并且工作正常:
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? |泰米尔喜剧网络系列 | Being Thamizhan已成功安排在2018-05-23 08:45 PM
关于html - Swift - 将 HTML 文本转换为属性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506888/