I am trying to create a multiline UILabel with an NSMutableAttributedString. This works fine when I assign an attribute to the complete string like this:
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(0, [string length])];
contentLabel.attributedText = string;
But I what I need is to apply a number of attributes for different subranges of the NSAttributedString (to bold certain words).
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(3, 5)];
contentLabel.attributedText = string;
What I am finding is that if I do this, the text isn't rendered over multiple lines in the label anymore. It is rendered as a single line, centered vertically in the label's frame.
Is there something I'm missing here?
As discussed in the question's comments, the code presented in the question actually works correctly, and does render the attributed string as intended. (The problem was elsewhere in my code)