Parsing HTML into Nsattributedtext - How to Set Font

Parsing HTML into NSAttributedText - how to set font?

Figured it out. Bit of a bear, and maybe not the best answer.

This code will go through all the font changes. I know that it is using "Times New Roman" and "Times New Roman BoldMT" for the fonts.
But regardless, this will find the bold fonts and let me reset them. I can also reset the size while I'm at it.

I honestly hope/think there is a way to set this up at parse time, but I can't find it if there is.

    NSRange range = (NSRange){0,[str length]};
[str enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
UIFont* currentFont = value;
UIFont *replacementFont = nil;

if ([currentFont.fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound) {
replacementFont = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:25.0f];
} else {
replacementFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0f];
}

[str addAttribute:NSFontAttributeName value:replacementFont range:range];
}];

NSAttributedString setting font size - swift

You are convert html to NSAttributedString?
You can append style to the string source.

example: https://stackoverflow.com/a/41519178/4368670

extension String {
func htmlToAttributedString(fontName: String = "Chalkduster", fontSize: Float = 72) -> NSAttributedString? {
let style = "<style>body { font-family: '\(fontName)'; font-size:\(fontSize)px; }</style>"
guard let data = (self + style).data(using: .utf8) else {
return nil
}
return try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
}
}
let html = "<div>content</div>"
lebal.attributedText = html.htmlToAttributedString()

result:

result

NSAttributedString: how to parse html tags and add attributes

Ok, I got the solution, maybe it will help anyone else.

Note, that my strings are strictly multi lined, so it's easy first split them, then add needed font and size to the parts, and then add paragraph styling.

I've played with order of parsing tags/styling fonts/styling paragraph, and at every case something was missed. If you don't need to separate line as multiline in strict order, just don't do mapping. Otherwise, you can miss breaking while styling or parsing tags.
Sample Image

 descriptionLabel.attributedText = getAttributedDescriptionText(for: "Register and get <b>all</b>\n<b>rewards cards</b> of our partners\n<b>in one</b> universal <b>card</b>", fontDescription: "ProximaNova-Regular", fontSize: 15)   



func getAttributedDescriptionText(for descriptionString: String, fontDescription: String, fontSize: Int) -> NSAttributedString? {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.alignment = .center
paragraphStyle.minimumLineHeight = 18.0

let attributedString = NSMutableAttributedString()
let splits = descriptionString.components(separatedBy: "\n")
_ = splits.map { string in
let modifiedFont = String(format:"<span style=\"font-family: '\(fontDescription)'; font-size: \(fontSize)\">%@</span>", string)
let data = modifiedFont.data(using: String.Encoding.unicode, allowLossyConversion: true)
let attr = try? NSMutableAttributedString(
data: data ?? Data(),
options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
],
documentAttributes: nil
)
attributedString.append(attr ?? NSMutableAttributedString())
if string != splits.last {
attributedString.append(NSAttributedString(string: "\n"))
}
}
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
return attributedString
}

Setting font size doesn't work after parsing simple HTML into NSAttributedString

I tried a few things but none of them worked. So I'm already parsing the HTML why not use inline CSS syntax?

<p style='font-size:17px'><strong>I'm bold.</strong><br/>http://www.google.com</p>


Related Topics



Leave a reply



Submit