Reputation: 8918
I would like to have label that has 4 lines. If text is not long enough for 4 lines, nothing happens. But if text is 4 lines or longer I want it to have a little different color just for last line.
Is there easy way to do this. I know i can with attributed string change font of label, but how do i get text that is in forth line?
Upvotes: 2
Views: 1429
Reputation: 33101
Use NSAttributedString to format paragraphs, lines, words or even single characters how ever you want. To get the text on the 4th line, separate your text on its \n
characters.
If you don't have any \n
, you can use getLineStart:end:contentsEnd:forRange:
, adapted from here
NSString *string = /* assume this exists */;
unsigned length = [string length];
unsigned lineStart = 0, lineEnd = 0, contentsEnd = 0;
NSMutableArray *lines = [NSMutableArray array];
NSRange currentRange;
while (lineEnd < length) {
[string getLineStart:&lineStart end:&lineEnd
contentsEnd:&contentsEnd forRange:NSMakeRange(lineEnd, 0)];
currentRange = NSMakeRange(lineStart, contentsEnd - lineStart);
[lines addObject:[string substringWithRange:currentRange]];
}
EDIT
After rereading the question, this may not be exactly what you are after. Check out the full answer here:
Upvotes: 1
Reputation: 2835
In iOS 6+ you can render attributed strings using the attributedText property of UILabel.
Following a code example:
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Hello. That is a test attributed string."];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(3,5)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(10,7)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];
label.attributedText = str;
As you can see in the code you can select a different color text for the different range of characters. In your case you can put the different font color for the chars in the string for the last line. In order to check the range of chars for the last line you can use:
NSUInteger characterCount = [myString length];
And then characterCount divided for number of chars you can put in each line depending on the width of it.
Upvotes: 0