0

In my app, i will get a html string in the format of

<p style = "text-align: center;"><strong>"some text in here</strong></p>

I know how to convert this html string to an attributedString using the following function.

[[NSAttributedString alloc] initWithData:[aboutData dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];

But the problem is, i wish to retain the all the attributes of the attained AttributedString, but be able to change either font size, font family and paragraph style of this attained attributedString.

For example, if i attain a bold attributedString from this html, how can I change the font size or font family of this particular string without changing its bold state?

How do i do that?

Thanks!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
progammingBeignner
  • 936
  • 1
  • 8
  • 19
  • http://stackoverflow.com/questions/19921972/parsing-html-into-nsattributedtext-how-to-set-font http://stackoverflow.com/questions/25401742/apply-custom-font-to-attributed-string-which-converts-from-html-string http://stackoverflow.com/questions/41412963/swift-change-font-on-an-html-string-that-has-its-own-styles/41413014#41413014 – Larme Apr 20 '17 at 14:03

1 Answers1

0
text.enumerateAttributes(
   in: NSRange.init(location: 0, length: text.length), 
   options: NSAttributedString.EnumerationOptions(rawValue: 0)
) { (attributes, range, pointer) in
    //GET ATTRIBUTES HERE
    if let font = attributes["NSFont"] as? UIFont {

    }    
}

This should get you all the attributes. Might be a better way to parse them but this can be a good start for you.

Luzo
  • 1,336
  • 10
  • 15
  • =>`attributes["NSFont"]` => `attributes[NSFontAttributeName]`, no? – Larme Apr 20 '17 at 14:02
  • I checked it in debugger, there was only "NSFont" – Luzo Apr 20 '17 at 14:05
  • 1
    `NSFontAttributeName` is a const defined by iOS, and is currently equals to `NSFont`. But in the future, if Apple change its value to `UIFont` for iOS and `NSFont` to OSX, which could make sense, your code won't work anymore. When you add the attribute yourself, you use `NSFontAttributeName`/ – Larme Apr 20 '17 at 14:08