你好我有一个字符串,我想写在Swift中的文本文档。但是,因为文本文档有换行符,所以字符串似乎是HTML格式。 这就是我想要做的事情:
//Covert str1 to str2
var str1 = "1<div>2</div><div>3</div><div>4</div>"
var str2 = "1
2
3
4" //Text document will have text that looks like this (With line breaks)
答案 0 :(得分:1)
您可以尝试使用NSAttributedString:
let htmlString = "1<div>2</div><div>3</div><div>4</div>"
NSAttributedString(data: htmlString.dataUsingEncoding(NSUnicodeStringEncoding)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil);
这会产生:
"1\n2\n3\n4\n"
答案 1 :(得分:1)
Swift 3.0:你可以直接将它弹出到Xcode的游乐场来检查它。
let htmlString = "1<div>2</div><div>3</div><div>4</div>"
func getHtmlFormat(fromString htmlString: String) -> NSAttributedString? {
guard let htmlData = htmlString.data(using: String.Encoding.unicode) else
{
print("Could not get htmlData")
return nil
}
do {
return try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch let error {
print(error)
return nil
}
}
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
textView.attributedText = getHtmlFormat(fromString: htmlString)