I have a UITextView with attributed text and allowsEditingTextAttributes set to true.
I\'m trying to convert the attributed st
Please check it once this work for me. You can update font style and family also by using below functions.
var htmlStr = "\n\n\n\n\n \n\n\n\n\nThis is pikes AsD this is finding error
\n\n\n"
htmlStr = htmlStr.replacingOccurrences(of: "\n", with: "")
htmlStr = htmlStr.replacingOccurrences(of: "\\", with: "")
//Send htmlStr to server and when you will get back it from
// then convert html string to attributed string by below line
let str = Self.htmlToAttributedString(html: htmlStr,fontSize :17, fontName:"Times New Roman")
self.tfEmail.attributedText = str
//Function for attributed string from html string
func htmlToAttributedString(html:String,fontSize:CGFloat = 15.0, fontName : String = "NunitoSans-Regular",ignorFontBold: Bool = false) -> NSAttributedString {
let attr = (try? NSAttributedString(htmlString: html, font: UIFont(name: fontName, size: fontSize),ignorFontBold: ignorFontBold)) ?? NSAttributedString()
return attr
}
//Extension for NSAttribute string
extension NSAttributedString {
convenience init(htmlString html: String, font: UIFont? = nil, useDocumentFontSize: Bool = false, ignorFontBold: Bool = false) throws {
let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
let data = html.data(using: .utf8, allowLossyConversion: true)
guard (data != nil), let fontFamily = font?.familyName, let attr = try? NSMutableAttributedString(data: data!, options: options, documentAttributes: nil) else {
try self.init(data: data ?? Data(html.utf8), options: options, documentAttributes: nil)
return
}
let fontSize: CGFloat? = useDocumentFontSize ? nil : font!.pointSize
let range = NSRange(location: 0, length: attr.length)
attr.enumerateAttribute(.font, in: range, options: .longestEffectiveRangeNotRequired) { attrib, range, _ in
if let htmlFont = attrib as? UIFont {
let traits = htmlFont.fontDescriptor.symbolicTraits
var descrip = htmlFont.fontDescriptor.withFamily(fontFamily)
if ignorFontBold == false{
if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitBold.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitBold)!
}
if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitItalic.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitItalic) ?? descrip
}
}
attr.addAttribute(.font, value: UIFont(descriptor: descrip, size: fontSize ?? htmlFont.pointSize), range: range)
}
}
self.init(attributedString: attr)
}
}