0

In iOS 7 we gained the ability to convert an HTML string into an NSAttributedString, like this:

NSString *html = @"<bold>Wow!</bold> Now <em>iOS</em> can create <h3>NSAttributedString</h3> from HTMLs!";
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};

NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil];

We also have the ability to provide default values for HTML that doesn't specify certain attributes using the NSDefaultAttributesDocumentAttribute option.

My question is: is there a way to tell NSAttributedString to ignore certain attributes it sees in the HTML (e.g. color) and instead use one that I provide? In other words, I want to provide an override attribute value, not a default.

pietrorea
  • 841
  • 6
  • 14
  • You may want to try changing the HTML source as found http://stackoverflow.com/a/21759504/1535038 – James Paolantonio Feb 17 '15 at 18:59
  • The HTML comes from a server response, so I can't change without tons of string manipulation. – pietrorea Feb 17 '15 at 19:14
  • I would either iterate over the attributes you want to edit, or run the html though an xml parser and set the attributes yourself. You could try subclassing NSAttributedString, or sizzling the setAttributes method to intercept the setter and changing the values as they are passed in. – ethyreal Feb 18 '15 at 22:32

1 Answers1

1

You can try enumerating through the string. For example, trying to change the link color.

NSMutableAttributedString *mttrString = [attrString mutableCopy];
[mutableString beginEditing];
[mutableString enumerateAttribute:NSLinkAttributeName
            inRange:NSMakeRange(0, res.length)
            options:0
         usingBlock:^(id value, NSRange range, BOOL *stop) {
             if (value) {
                 UIFont *oldFont = (UIFont *)value;
                 UIFont *newFont = [UIFont systemFontOfSize:12.f];
                 [res addAttribute:NSFontAttributeName value:newFont range:range];
             }
         }];
[res endEditing];
attrString = mAttrString;

I haven't tried this, but you should be able to manipulate the string this way.

James Paolantonio
  • 2,194
  • 1
  • 15
  • 32