iOS: how to change colour/font of some characters of a string - ios

in my app i have to change the font of a part of string which comes from JSON response
> "<span class=\"drop_data_user\">Andrew James</span> liked your comment
> \"hiiiiiiiiiiiiiii\" that you posted."
to convert it in attributed string i am using the following code
NSAttributedString *attr = [[NSAttributedString alloc] initWithData:[NotificationTxt dataUsingEncoding:NSUTF8StringEncoding]
options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:#(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil];
I want to change the font colour of the sender

Also, you can use it as follows.
NSString *dateString = [NSString stringWithFormat:#"%#%#", #"Teslimat: ", selectedReservationModel.DateLabel];
NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString: dateString];
[attrS addAttribute:NSFontAttributeName value:[GenericUtility getOpenSansBoldFontSize:12] range:NSMakeRange(0, 8)];
[attrS addAttribute:NSFontAttributeName value:[GenericUtility getOpenSansRegularFontSize:12] range:NSMakeRange(9, selectedReservationModel.DateLabel.length)];
lblDeliveryDate.attributedText = attrS;

NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:#"My String"];
[attrS addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
[attrS addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(3, 6)];
self.myLabel.attributedText = attrS;
For fonts use
[attrS addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, 3)];

I believe the easiest way to fulfil your task is to use CSS inlined in the text, then parsing HTML as you do will change the color too (I'm using Swift syntax, but I believe you can easily convert it to ObjC):
let text = "<span class=\"drop_data_user\">Andrew James</span> liked your comment \"hiiiiiiiiiiiiiii\" that you posted."
let colouredAuthorText = "\(text)<style>.drop_data_user { color: #FEB600; }</style>"
Then just parse colouredAuthorText (which is created by appending style to the original text) instead of the original, and you should be good to go.

Related

How to change properties of particular text in a label

I have a label and i set the text of the label programmatically. I want to set one of the word to be bold and the rest normal. However, i am unable to control the properties of the text. For example, I want this "This is an example" but am only able to achieve this "This is an example".
Try this:
NSString *text = #"This is an example";
NSString *textBold = #"example";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
[attributedString beginEditing];
[attributedString addAttribute:NSFontAttributeName
value:[UIFont boldSystemFontOfSize:20.0f]
range:[text rangeOfString:textBold]];
[attributedString endEditing];
[labelObj setAttributedText:attributedString];
Take a look at the attributedText property of the label. It lets you assign styled text using an NSAttributedString. Explaining how to build an NSAttributedString is beyond the scope of an SO answer, but you should be able to find ample information both in the Xcode help system and online.
Let me show you a demo about the attributedText.
NSDictionary*subStrAttribute1 = #{
NSForegroundColorAttributeName: [UIColor redColor],
NSStrikethroughStyleAttributeName:#2
};
NSDictionary *subStrAttribute2 =#{
NSForegroundColorAttributeName: [UIColor greenColor]
};
NSString *strDisplayText3 =#"Red and Green";
NSMutableAttributedString *attributedText3 = [[NSMutableAttributedString alloc] initWithString:strDisplayText3];
[attributedText3 setAttributes:subStrAttribute1 range:NSMakeRange(0,3)];
[attributedText3 setAttributes:subStrAttribute2 range:NSMakeRange(8,5)];
self.lblInfo3.attributedText= attributedText3;
Since ios6 uilabel supports attributed strings, So you can use it.
For your particular case below code will work-
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:#"This is an example"];
[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(11, 7)];
label.attributedText = string;

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];

Add a nsstring at the end of attributed string in textview iOS

I have a text like "Hello There" which will be a attributed string with red color. Then at the end of that attributed string I want to append a nsstring 'Who are you?' But whenever I append a nsstring, the whole string becomes normal nsstring and the property of the attributed string is being removed. My attempt so far:
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:#"Hello There"];
[attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,[attributeString length])];
NSMutableAttributedString *previousAttrString = [[NSMutableAttributedString alloc] initWithString:messageTextView.text];
[previousAttrString insertAttributedString: attributeString atIndex:location];
messageTextView.attributedText = previousAttrString;
messageTextView.font = [UIFont fontWithName:#"Helvetica" size:15];
NSString *messageWithContact = [NSString stringWithFormat: #"%# %#", messageTextView.text, #"Who are you?"];
messageTextView.text=messageWithContact;
What I did wrong? Please help me.
Replace the bottom lines
NSString *messageWithContact = [NSString stringWithFormat: #"%# %#", messageTextView.text, #"Who are you?"];
messageTextView.text=messageWithContact;
with
NSMutableAttributedString *newString = messageTextView.attibutedText;
[newString appendAttributedString: [[NSAttributedString alloc] initWithString: #"Who are you?"];
messageTextView.attibutedText = newString;

Why does this NSMutableAttributedString addAttribute work only if I use a mutableCopy

I have the following code :
NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:#"• Get Tested Son"];
NSMutableAttributedString *boldS = [[NSMutableAttributedString alloc] initWithString:#"Son"];
[boldS addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(0, boldS.length)];
[attrS replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
withAttributedString:boldS];
As you can see, I want to bold the Son part. This does not work if I do the above statements but only works if I do :
[[attrS mutableCopy] replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
withAttributedString:boldS];
What might be the reason for that?
addAttribute works regardless of whether you take a mutableCopy. Your question is based on a false assumption. It therefore has no answer.
Run this:
NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:#"• Get Tested Son"];
NSMutableAttributedString *boldS = [[NSMutableAttributedString alloc] initWithString:#"Son"];
UIFont *someBoldFont = [UIFont fontWithName:#"Arial" size:23.0f];
[boldS addAttribute:NSFontAttributeName value:someBoldFont range:NSMakeRange(0, boldS.length)];
NSMutableAttributedString *attrSCopy = [attrS mutableCopy];
[attrS replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
withAttributedString:boldS];
[attrSCopy replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
withAttributedString:boldS];
NSLog(#"%#", [attrS isEqual:attrSCopy] ? #"equal" : #"different");
It will output equal. Comment out the replaceCharactersInRange: for either attrS or attrSCopy and it will output different.

How to show multiple line text that has different font without using multiple Labels

I have to show a text paragraph that contains few words in bold font. ex.
If I use different labels then on changing the orientation it does not resize properly.
Can anyone tell me what can the best way to do it.
You can use an UITextView using NSAttributedString (have a look to the apple doc)
And you have an explanation of how to use it here.
You can find the range of your word and change the font or the color or whatever using :
- (IBAction)colorWord:(id)sender {
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSArray *words = [self.text.text componentsSeparatedByString:#" "];
for (NSString *word in words)
{
if ([word hasPrefix:#"#"])
{
NSRange range=[self.text.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
}
[self.text setAttributedText:string];
}
You have to use a NSAttributedString and assign it to the UITextField, this is an example:
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
NSMutableAttributedString *myAttributedString = [[NSMutableAttributedString alloc] initWithString:yourString];
[myAttributedString addAttribute:NSFontAttributeName
value:boldFont
range:NSMakeRange(0, 2)];
[myAttributedString addAttribute:NSFontAttributeName
value:regularFont
range:NSMakeRange(3, 5)];
[self.description setAttributedText:myAttributedString];
Find all the doc here:
NSAttributedString
For your case, you can use a webView and load it with your string:
[webView loadHTMLString:[NSString stringWithFormat:#"<html><body style=\"background-color: transparent;\">This is <b><i>Test</b></i> dummy text ..</body></html>"] baseURL:nil];

Resources