Display HTML text in UILabel iphone

前端 未结 11 1996
借酒劲吻你
借酒劲吻你 2020-12-02 14:39

I am getting a HTML Response from a webservice Below is the HTML I am getting in response

TopicGud mrng.

\\n
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 15:06

    **// Swift 4 compatible | with setting of colour and font options:**
    
    // add following extension to String:
    
            func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
    
                    let sizeInPx = (size * 0.75)
    
                    do {
                      let htmlCSSString = " \(self)"
    
                      guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                        return nil
                      }
    
                      return try NSAttributedString(data: data,
                                                    options: [.documentType: NSAttributedString.DocumentType.html,
                                                              .characterEncoding: String.Encoding.utf8.rawValue],
                                                    documentAttributes: nil)
                    } catch {
                      print("error: ", error)
                      return nil
                    }
                  }
    
            // add following extension to UIColor:
    
            extension UIColor{
    
              var hexString:String? {
                if let components = self.cgColor.components {
                  let r = components[0]
                  let g = components[1]
                  let b = components[2]
                  return  String(format: "%02X%02X%02X", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
                }
                return nil
              }
            }
    
        // Sample Use:
    
        yourLabel.attributedText = locationTitle.htmlAttributed(family: yourLabel.font.fontName,
                                                                               size: yourLabel.font.pointSize,
                                                                               color: yourLabel.textColor)
    

提交回复
热议问题