HTML转Swift富文本会多一行

在开发项目中,发现后台给返回的html字符串中,有的有

标签,有的没有,html字符串在转换成iOS富文本字符串时,会莫名多一行,网络上搜索了半天没有解决方法,于是另辟蹊径,最后发现在转换成iOS富文本时会多一个\n,那么这就好解决了,去掉就可以了


1668042350990.jpg
if let content:String = model?.html{
  //转成data
  if let data:Data = content.data(using: .unicode){
    do{
      //html字符串转成iOS富文本
      let att:NSMutableAttributedString = try NSMutableAttributedString(data: data, options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)
      //添加富文本样式
      att.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17)], range: NSRange(location: 0, length: att.length))
      let n = NSAttributedString(string: "\n")
      if att.string.hasSuffix("\n") {
        //删除\n
        att.deleteCharacters(in: NSRange(location: att.length - n.length, length: n.length))
      }
      contentLabel.attributedText = att
    }catch{

    }
  }
}
1668042374561.jpg

你可能感兴趣的:(HTML转Swift富文本会多一行)