问题描述
我正在使用iOS(Swift)应用程序。我收到一些服务器响应,如下所示。
"description":"This is sample text to show in UI. When doing everyday activities.\u003cbr /\u003eclass is a strong predictor of life,and again sample text here.\u003cbr /\u003eSample text can show here also."
因此,上面的文本有3个段落,我试图在Textview
中显示它们,但是用新行而不是新段落以纯文本显示。
override func viewDidLoad() {
super.viewDidLoad()
let description = jsonResponse["description"] as! String
self.textView.attributedText = description.htmlAttributedString()
}
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16,allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],documentAttributes: nil) else { return nil }
return html
}
}
The issue is it is showing text,But like new line showing instead of new paragraph. How to fix this?
解决方法
我已通过解决此问题,并将服务器转换为json序列化后,特殊字符代码显示为
因此,我已修复如下问题
let description = jsonResponse["description"] as! String
let formattedString = description.replacingOccurrences(of: "<br />",with: " \n\n")
self.textView.text = formattedString