在我的一个模块中,我希望使用NSAttributedString将多语言HTML文本(英语和泰米尔语)显示为一个UILabel。如果课文是纯英语的,我可以把它显示为我的愿望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 ?泰米尔喜剧网络系列被安排在2018-05-23 08:45
电流输出
IPL泰米尔网络系列第3集&*$3!@#$@^&$&^%$ Swetha吗? 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 ?? ""
}
}发布于 2018-05-24 10:38:24
我用您的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 ?泰米尔喜剧网络系列被安排在2018-05-23 08:45
发布于 2022-06-30 13:57:14
var htmlAttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8), options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var htmlString: String {
return htmlAttributedString?.string ?? ""
}使用它,您可以得到字符串本身,而不是属性化字符串。请确保您使用的是主线程,否则它可能崩溃。
https://stackoverflow.com/questions/50506888
复制相似问题