我想将HTML Tag
转换为String
,我使用enum
根据我需要执行某些操作的长度来查找String
的内容长度。
我的modal
课程,
class PostViewModel {
var content: TextContent
enum TextContent {
case expanded(String)
case collapsed(String)
static func == (lhs: TextContent, rhs: TextContent) -> Bool {
switch lhs {
case .collapsed(let content):
if case collapsed(content) = rhs {
return true
}
return false
case .expanded(let content):
if case expanded(content) = rhs {
return true
}
return false
}
}
}
}
我在cellForItem(at index: Int)
,
func applyVerticalSizeConcernedRendering(fromViewModel viewModel: PostViewModel) {
switch viewModel.content {
case .collapsed(let content):
let str = content.html2String
print(str)
case .expanded(let content):
break
}
}
html2String
extension
等级为String
extension String {
var html2AttributedString: NSMutableAttributedString? {
guard let data = data(using: String.Encoding.utf8) else { return nil }
let attrs: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
do {
let attrStr = try NSMutableAttributedString(data: data, options: attrs, documentAttributes: nil)
return attrStr
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
问题是将HTML标记转换为String
它在这里崩溃,
let attrStr = try NSMutableAttributedString(data: data, options: attrs, documentAttributes: nil)
String
不为空
以下是示例HTML String
,
<strong>I want to test HTML Tags<br><\/strong>dsfhjdjf sjdfdj djfjdfj djkf dfjdhf <strong>adjf<br>asks <\/strong>djfdkf<br><strong>dfdjk dkfjdk <\/strong>dfjik iai <strong>adsfhj<\/strong>
当我尝试使用硬编码值时,此功能正常,但只有当我从String
enum
时它才会崩溃
崩溃日志是,
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
有人可以帮忙吗?
答案 0 :(得分:1)
试试这个,不需要做你已完成的整个过程:
extension String {
var htmlAttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var htmlString: String {
return htmlAttributedString?.string ?? ""
}
<强>用法:强>
let html = "<strong>I want to test HTML Tags<br></strong>dsfhjdjf sjdfdj djfjdfj djkf dfjdhf <strong>adjf<br>asks</strong>djfdkf<br><strong>dfdjk dkfjdk </strong>dfjik iai <strong>adsfhj</strong>"
let str = html.htmlString
所以你基本上只是在你的字符串上使用String extension
。这是我在项目中使用的
Here是您可以尝试的示例项目。