1

I am parsing simple HTML into an attributed string (for iOS 6), and I can't seem to get nested attributes to work. eg:

This <font color="red">is <i>what</i> I mean</font> to achieve.

I am correctly applying the attributes, but the italicization never takes affect, unless it is done on a range that the font color doesn't affect. My googling has not brought up any related issues, and I'm wondering if NSAttributedString even supports this at all, or if attributes ranges must be non overlapping.

EDIT:

I've reworded the question to be clearer. The answer to the question is a resounding NO, you must specify all attributes for a given range in a single attribute dictionary, they do not combine. I've accepted a reasonable answer to the original question as correct.

eclectocrat
  • 260
  • 1
  • 3
  • 9

2 Answers2

1

You can achieve the result you want with NSMutableAttributedString. You simply need to set each attribute separately. E.g.

NSString *string = @"This is a test";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string attributes:nil];

NSMutableDictionary *attributes = [@{NSForegroundColorAttributeName: [UIColor redColor]} mutableCopy];

[string setAttributes:attributes range:[string rangeOfString:@"is a test"];

[attributes setObject:font forKey:NSFontAttributeName];

[string setAttributes:attributes range:[string rangeOfString:@"test"];
Gianluca Tranchedone
  • 3,598
  • 1
  • 18
  • 33
  • This doesn't result in the effect I am looking for. The font attribute overwrites the color attribute, I want them to stack. Thanks though, I guess that means attributes don't nest. – eclectocrat Jan 27 '14 at 14:47
  • You're right, I've edited my answer with the right thing to do. – Gianluca Tranchedone Jan 27 '14 at 15:14
  • `addAttribute` should be better – Larme Jan 27 '14 at 15:47
  • Ok, so this is the right way to achieve my example, but the question was poorly worded. I meant to ask if attributes stack when their ranges overlap/nest, and the answer is NO, you must do as described in this post and specify each range with all of it's attributes. – eclectocrat Jan 27 '14 at 15:55
1

Yes, you can have specific attributes for specific ranges. As many as you want.

hfossli
  • 22,616
  • 10
  • 116
  • 130