在開發(fā)項目中,發(fā)現(xiàn)后臺給返回的html字符串中,有的有<p>標簽,有的沒有,html字符串在轉換成iOS富文本字符串時,會莫名多一行,網(wǎng)絡上搜索了半天沒有解決方法,于是另辟蹊徑,最后發(fā)現(xiàn)在轉換成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