pietrorea
pietrorea

Reputation: 898

Use NSAttributedString to overwrite HTML attributes

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.

Upvotes: 0

Views: 765

Answers (1)

James Paolantonio
James Paolantonio

Reputation: 2194

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.

Upvotes: 1

Related Questions