Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add multiple attributes to NSAttributedString and encode HTML

I want to encode a text to HTML and apply multiple attributes at the same time.

My Swift 4 code looks like this:

let attributedString = try? NSMutableAttributedString(
                data: tweetContent.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
                options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
                documentAttributes: nil)

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.4

let attributes = [NSAttributedStringKey.font: UIFont(name: "Roboto-Regular", size: 17.0)!,
                NSAttributedStringKey.paragraphStyle: paragraphStyle]

let textRangeForFont : NSRange = NSMakeRange(0, attributedString!.length)
attributedString?.addAttributes(attributes, range: textRangeForFont)

tweetContent represents the string that I want to set a font for and which should be encoded for HTML. In the end, I want to set as many attributes as I like to that string without loosing the html encoding.

However, this code results in displaying the placeholder text which I set up in the storyboard.

Any help is appreciated!

like image 707
WalterBeiter Avatar asked Feb 24 '26 13:02

WalterBeiter


1 Answers

I forgot to add the attributed text to the textview:

textView.attributedText = attributedString 

This solved my problem.

like image 92
WalterBeiter Avatar answered Feb 27 '26 04:02

WalterBeiter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!