html - Swift - 将 HTML 文本转换为属性字符串

标签 html ios swift nsattributedstring

在我的一个模块中,我想使用 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/

相关文章:

html - 删除图库框上的最右边距

javascript - 根据点击的元素切换多个元素的类

javascript - 当字符插入输入文本框时制表符光标

ios - Swift:使用完成处理程序从另一个 ViewController 通知

ios - 在IOS运行时添加字体到textarea或webview?

sorting - 使用点击在表格 View 中移动行 - Swift

html - 如何在 div 中使用带有文本的剪辑路径?

iphone - 用于选择器 View iPhone 的 JSON 数组

swift - 使用 Swift 的 CoreLocation 获取最近的企业名称

swift - Apple Watch 加速度计是否提供正确的数据?