如何在swift 3 ios中使用html标签和图像显示内容文本

时间:2017-02-06 05:28:17

标签: html ios swift webview

我从API获取包含html tagspictures的文字。如何显示它以及我需要显示的位置,我的意思是UILabel还是WebView? 我尝试使用NSAttributedString,但不是我需要的。

平台iOS 9,Swift 3

2 个答案:

答案 0 :(得分:5)

我找到了方法。 我在Info.plist

  

应用传输安全设置 - >允许任意负载 - >是

图像正在显示。

代码:

DispatchQueue.main.async {
    let attrStr = try! NSAttributedString(
                data: (self.detailLabelText?.data(using: String.Encoding.unicode, allowLossyConversion: true)!)!,
                options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                documentAttributes: nil)

   self.detailLabel.attributedText = attrStr
   self.detailLabel.textAlignment = NSTextAlignment.justified
   self.detailLabel.contentMode = .scaleToFill
   self.detailLabel.font = UIFont(name: "PTSans-Narrow", size: 18.0)
}

detailLabel.adjustsFontSizeToFitWidth = true
detailLabel.sizeToFit()

答案 1 :(得分:3)

您可以在webView中加载html标签

 func loadHtmlCode() {
        let htmlCode = "<html><head><title>Wonderful web</title></head> <body><p>wonderful web. loading html code in <strong>UIWebView</strong></></body>"
        webView.loadHTMLString(htmlCode, baseURL: nil)
    }