Formatting multi line text in UILabel? - ios

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?

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:

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.

Related

Find last line of multiline label and change colour [duplicate]

This question already has answers here:
UILabel Text with Multiple Font Colors
(8 answers)
Closed 4 years ago.
I m working on multi line text with different colour.The following code to change the first line colour But want to change the last line colour.
NSRange rangeOfNewLine = [label.text rangeOfString:#"\n"];
NSRange newRange = NSMakeRange(0, rangeOfNewLine.location);
[text addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:newRange];
NSArray* lines = [label.text componentsSeparatedByString:#"\n"];
NSString* lastLine = lines.lastObject;
NSRange rangeOfLastLine = [label.text rangeOfString:lastLine];
[text addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:rangeOfLastLine];
//NSString *myString = #"I have to replace text 'Dr Andrew Murphy, John Smith' ";
NSString *myString = #"Not a member?signin";
//Create mutable string from original one
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString];
//Fing range of the string you want to change colour
attributeText _label.attributedText = attString;
//If you need to change colour in more that one place just repeat it
NSRange range = [myString rangeOfString:#"signin"];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:(63/255.0) green:(163/255.0) blue:(158/255.0) alpha:1.0] range:range];
//Add it to the label - notice its not text property but it's
attributeText _label.attributedText = attString;

How to BOLD certain words within an NSString paragraph

I was wondering if it was possible to bold specific words within a text that is being held in an NSString.
I am able to bold, change the font of characters based on their location within the string using NSMutableAttributedString like this:
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:utf8String];
UIFont *boldFont = [UIFont boldSystemFontOfSize:18];
NSRange boldedRange = NSMakeRange(0, 9);
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFont
range:boldedRange];
[attrString endEditing];
But this changes the font of the first 9 characters in the String.
What I want is to put in Bold the following words should they be found within the string: "Questions", "Did you know" and "Further reading". Is this possible? The fact is that I don't know their position in the string.
I did have a look at the question suggesting this is a duplicate, but my question is not exactly the same and the answers provided did not help. I Need to find ranges within a string and then add them to an NSMutableAttributedString, and this is the bit I am asking help for. An answer has been provided that explains how to do that.
EDIT:
The supposed duplicate and its answer DO NOT answer the question. This question is more than just finding specific words within a paragraph, it is also about how to format them using NSMutableAttributedString. The answer provided below is the answer.
Thanks!
If you don't know substring position then you can use NSRange to find position of substring and using position you can make changes to the substring using NSMutableAttributedString class.
example :
UIFont *fontForlabel1 = [UIFont fontWithName:#"Helvetica-Bold" size:14.0];
UIFont *fontForlabel2 = [UIFont fontWithName:#"Helvetica-Bold" size:19.0];
UIFont *fontForlabel3 = [UIFont fontWithName:#"Helvetica" size:12.0];
NSString *text = #"Do you know that or did you know that?";
NSRange range;
UILabel *setlable;
NSMutableAttributedString * attributedString= [[NSMutableAttributedString alloc] initWithString:text];
range = [text rangeOfString:#"Do you know"];
[attributedString addAttributes:#{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:fontForlabel1} range:range];
range = [text rangeOfString:[#"or"];
[attributedString addAttributes:#{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:fontForlabel2} range:range];
range = [text rangeOfString:#"did you know that"];
[attributedString addAttributes:#{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:fontForlabel3} range:range];
setlable.attributedText=attributedString;

Display string having words with multiple formatting

In my app, I am displaying user comment that is fetched from the server. The comment contains user name, tag and some text in bold.
For example:
"Nancy tagged Clothing: Season 2, Episode 5. where do they find all the old clothes"
The words "Nancy" and "Clothing:" should be gray and orange color, respectively and "Season 2, Episode 5." should be bold.
I have tried using NSAttributedString but failed to achieve the above.
Following is the code I tried to change color but nothing changed. I am not very sure of how to use NSAttributedString.
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#:", tag.title]];
[title addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:246/255.0 green:139/255.0 blue:5/255.0 alpha:1.0f] range:NSMakeRange(0,[title length])];
self.tagCommentLabel.text = [NSString stringWithFormat:#"%# tagged %#: %# %#",tag.user.name , title, episode, tag.comment];
Can someone help me with a code as to how can I achieve the example sentence with the desired formatting?
NSAttributedString and NSString are two different things. If you want to add attributes to NSString (e.g. change the color of the text), you have to first make the NSString:
NSString *string = [NSString stringWithFormat:#"%# tagged %#: %# %#",tag.user.name , title, episode, tag.comment];
Then you make NSMutableAttributedString from your NSString and add attributes to it:
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:246/255.0 green:139/255.0 blue:5/255.0 alpha:1.0f] range:[string rangeOfString:title];
And when you want to display your attributed string, you should use .attributedText instead of .text:
self.tagCommentLabel.attributedText = attString;
You will have to add logic because I'm pretty sure you don't want to always color/bold this specific words, but here you go with a quick example:
NSString *title = #"Nancy tagged Clothing: Season 2, Episode 5. where do they find all the old clothes";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title];
// Color text for range of string
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor grayColor]
range:[title rangeOfString:#"Nancy"]];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor grayColor]
range:[title rangeOfString:#"Clothing"]];
// Bold (be careful, I have used system font with bold and 14.0 size, change the values as for yourself)
[attributedString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:14.0 weight:UIFontWeightBold]
range:[title rangeOfString:#"Season 2"]];
[attributedString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:14.0 weight:UIFontWeightBold]
range:[title rangeOfString:#"Season 5"]];
self.tagCommentLabel.attributesText = attributedString;
Edit: To make it work with your code, delete the line:
self.tagCommentLabel.text = [NSString stringWithFormat:#"%# tagged %#: %# %#",tag.user.name , title, episode, tag.comment];
Instead of mine assigning to title with static text, change it to:
NSString *title = [NSString stringWithFormat:#"%# tagged %#: %# %#",tag.user.name , title, episode, tag.comment];

Highlight selected character dynamically in iOS

I want to highlight selected character in iOS, as you an see in iPhone iOS 7 Notes app.
When you search for particular text the search character will be highlighted in the result displayed in UITableView.
Example:
"This is my name"
h - should 've blue color
y - should 've red color
The character customisation should be dynamic. I hope I've briefed enough.
Looking for excellent response buddies!
Try having a look at TextKit
This is a nice website that shows you the basics
I hope I understood your question..
You can easily achieve this by setting an attributed string to the text label in a UITableViewCell that shows an entry of your search results.
You would need to calculate ranges of the substrings that should be highlighted. You can do it using regular expressions as I wrote in my sample code. This way you can support multiple occurrences of the substring in a string.
Then, when you have the ranges you just apply special attributes and set the cell label's attributedText property.
The code could look like this:
NSString *searchTerm = ...;
NSString *text = #"This is a sample text that is super cool";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSString *pattern = [NSString stringWithFormat:#"(%#)", searchTerm];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:kNilOptions
error:nil];
NSRange range = NSMakeRange(0, text.length);
[regex enumerateMatchesInString:text
options:kNilOptions
range:range
usingBlock:^(NSTextCheckingResult *result,
NSMatchingFlags flags,
BOOL *stop)
{
NSRange subStringRange = [result rangeAtIndex:1];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor]
range:subStringRange];
}];
Then it's easy. You just set the UILabel's attributedText when creating a cell in tableView:cellForRowAtIndexPath: method.
This should point you to the right direction.
Use NsMutableAttributedString to highlight characters
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:display];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange([displayString length], ([details.notificationCount length]+2))];
displayLabel.attributedText = str;

NSMutableAttributedString crashes when changing fonts for different ranges

So I'm trying to change the colors of a NSMutableAttributedString but I keep getting an out of bounds exception error when I try to add multiple ranges (see below). If on the other hand I just do a single range from 0 to totalLength-1, there is no issue. I don't know why this is happening.
My code is below:
NSString *testString = #"This is my test string for this example";
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc] initWithString:testString];
int totalLength = [playerTurnString length];
[playerTurnString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor] range:NSMakeRange(0, 11)];
[playerTurnString addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor] range:NSMakeRange(12, totalLength-1)];
An NSRange is a location and a length, so when you do
NSMakeRange(12, totalLength-1)
Your length is 12 too long and therefore exceeds the range of the string. You're trying to use it as a start and end location but that isn't how it works.

Resources