首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift -将HTML文本转换为属性化字符串

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

Stack Overflow用户
提问于 2018-05-24 10:23:59
回答 2查看 9.8K关注 0票数 6

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

HTML内容

代码语言:javascript
复制
<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上。

注意:我尝试用下面的代码片段来存档

代码语言:javascript
复制
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 ?? ""
}
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-24 10:38:24

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

代码语言:javascript
复制
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

票数 19
EN

Stack Overflow用户

发布于 2022-06-30 13:57:14

代码语言:javascript
复制
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 ?? ""
    }

使用它,您可以得到字符串本身,而不是属性化字符串。请确保您使用的是主线程,否则它可能崩溃。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50506888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档