如何使用 HTML 数据在 Swift UITextView 中正确显示某些字符

How to get certain characters to display correctly in Swift UITextView with HTML data

我在 UITextView 中成功呈现 HTML 数据,但某些字符 (• — “ ” ‘ ’ º ©) 显示不正确。

例如:“abilities – and”呈现为“abilities – and

这是我正在使用的代码示例:

let inputString = "<span style='font-family:-apple-system;font-size:17'>
  <h2 style=font-weight:800;color:0282F8>Sample Heading</h2>
  <p style=font-weight:300>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas congue posuere neque a pretium. Nullam viverra ex tortor, quis dictum urna pulvinar non. In tristique nisi libero, nec ornare orci consequat suscipit. Maecenas quis elit magna. Donec finibus semper nulla sit amet dignissim. Vestibulum consectetur ullamcorper justo. Ut tincidunt nisi ut porta ornare.</p>
  <p style=font-weight:300>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas congue posuere neque a pretium. Nullam viverra ex tortor, quis dictum urna pulvinar non. In tristique nisi libero, nec ornare orci consequat suscipit. Maecenas quis elit magna. Donec finibus semper nulla sit amet dignissim. Vestibulum consectetur ullamcorper justo. Ut tincidunt nisi ut porta ornare.</p>
  <h2 style=font-weight:800;color:0282F8>Sample Heading</h2>
  <p style=font-weight:300>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas congue posuere neque a pretium. Nullam viverra ex tortor, quis dictum urna pulvinar non. In tristique nisi libero, nec ornare orci consequat suscipit. Maecenas quis elit magna. Donec finibus semper nulla sit amet dignissim. Vestibulum consectetur ullamcorper justo. Ut tincidunt nisi ut porta ornare.</p>
</span>"

let data = Data(self.inputString.utf8)
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
                uiView.isEditable = false
                uiView.attributedText = attributedString
}

代码工作正常,除了那些字符。

我可以添加一些对我的 inputString 有用的东西吗?

谢谢

您可以尝试以下方法

let inputString = """
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
        </head>
        <body>
                    <span style='font-family:-apple-system;font-size:17'>
                      <h2 style=font-weight:800;color:0282F8>Sample Heading</h2>
                      <p style=font-weight:300>abilities – and  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas congue posuere neque a pretium. Nullam viverra ex tortor, quis dictum urna pulvinar non. In tristique nisi libero, nec ornare orci consequat suscipit. Maecenas quis elit magna. Donec finibus semper nulla sit amet dignissim. Vestibulum consectetur ullamcorper justo. Ut tincidunt nisi ut porta ornare.</p>
                    </span>
        </body>
        </html>

请注意

<meta charset="UTF-8">