斯威夫特 - 转换HTML文本属性串

问题描述 投票:2回答:1

在我的模块的一个,我想表明使用的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年5月23日下午8时45分

电流输出

IPL泰米尔网系列情节#3 | &* $%!@#$ @ ^&$&^%$ Swetha? |泰米尔喜剧网络系列|正在Thamizhan已成功定于2018年5月23日下午8时45分

注:我试着用下面的代码片段归档此

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个回答
8
投票

我想这个解决方案与您的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年5月23日下午8时45分

© www.soinside.com 2019 - 2024. All rights reserved.