How change the font of attributed string in iOS? [duplicate] - ios

This question already has an answer here:
Apply Custom font to Attributed string Which Converts from HTML String
(1 answer)
Closed 6 years ago.
I have added attributed string on label.I am displaying html text which works fine but by default it is always showing Times new roman family. Please tell how can i change text family.
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[inst.desc dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

Try with this:
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[inst.desc dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSMutableAttributedString *newString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
NSRange range = (NSRange){0,[newString length]};
[newString enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
UIFont *replacementFont = [UIFont fontWithName:#"Palatino-Roman" size:14.0];
[newString addAttribute:NSFontAttributeName value:replacementFont range:range];
}];
self.label.attributedText = newString;

you can do like that:
NSDictionary *attrDict = #{
NSFontAttributeName : [UIFont fontWithName:Arial size:16.0],
NSForegroundColorAttributeName : [UIColor redColor]
};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:#"string" attributes:attrDict];

Related

UILabel display emojis

I have a UILabel which is displaying emojis incorrectly.
Here is a screenshot from iOS app:
And here is a screenshot from Android app which is displaying the same text with the emoji correctly.
I have tried answers from here but they did not help.
Example string : "تم البيع والله يبارك للمشتري♥️"
Here is the code:
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:comment.body];
UIFont *cellFont = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
NSDictionary *attributesDictionary;
NSMutableParagraphStyle *paragraphStyle =
[[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10;
paragraphStyle.alignment = NSTextAlignmentRight;
paragraphStyle.allowsDefaultTighteningForTruncation = true;
attributesDictionary = #{
NSParagraphStyleAttributeName : paragraphStyle,
NSFontAttributeName : cellFont,
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)
};
[str addAttributes:attributesDictionary
range:NSMakeRange(0, str.length)];
cell.commentTextLabel.attributedText = str;
Any help would be appreciated.
Use the emoji's unicode.
in your case, the unicode for the red heart is: U+2764 U+FE0F .
Objective C code :
cell.commentTextLabel.text = #"تم البيع والله يبارك للمشتري \U00002764 \U0000FE0F";
Swift code:
cell.commentTextLabel.text = "تم البيع والله يبارك للمشتري \u{2764} \u{FE0F}"
For more emojis, In Xcode go Edit -> Emoji & Symbols, choose an emoji then right click on it and click Copy Character Info Button. Paste it and you will get for the red heart:
❤️
red heart
Unicode: U+2764 U+FE0F, UTF-8: E2 9D A4 EF B8 8F
I was able to solve this issue by using the following code:
NSData *data = [comment.body dataUsingEncoding:NSUTF16StringEncoding allowLossyConversion:false];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc ] initWithData:data options:#{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
UIFont *cellFont = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
NSDictionary *attributesDictionary;
NSMutableParagraphStyle *paragraphStyle =
[[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10;
paragraphStyle.alignment = NSTextAlignmentRight;
attributesDictionary = #{
NSParagraphStyleAttributeName : paragraphStyle,
NSFontAttributeName : cellFont
};
[str addAttributes:attributesDictionary range:NSMakeRange(0, str.length)];
cell.commentTextLabel.attributedText = str;
In here comment.body is the string fetched from server which contains the emoji.
The result was like this:
Thanks to Larme for his help in the comments.

NSMutableAttributedString hides part of a NSString - iOS

I have a NSString with this format:
<p>When: Every day except Monday at 11:45am
</p><p>Where: Main Pool</p><p><br></p><p>Get refreshed in the main pool during the warm sunny days whilst participating in our animation's fit activities. Enjoy our aqua fitness 6 times per week.<br></p>
I use this code to display the html attributes and also set a default font size and color:
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[self.Description dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
__block BOOL found = NO;
[attrStr beginEditing];
[attrStr enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrStr.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value) {
UIFont *oldFont = (UIFont *)value;
UIFont *newFont = [oldFont fontWithSize:16];
[attrStr addAttribute:NSFontAttributeName value:newFont range:range];
[attrStr addAttribute:NSForegroundColorAttributeName
value:[UIColor darkGrayColor]
range:range];
found = YES;
}
}];
[attrStr endEditing];
cell.descLbl.attributedText = attrStr;
Those words doesn't show up:
fitness 6 times per week.<br></p>
it only shows some weird dots-lines at the top of where the letters should be.
I believe the problem is when I change the String to unicode, the length of the String changes and so the range. How can I fix this?

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

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.

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.

NSDocumentTypeDocumentAttribute doesn't work with NSFontAttributeName

Story
App receives strings with html tags that were edited in CMS. App receives that strings and put to UILabel. Not so long ago html tags were added to this strings. Obviously strings with html tags looks fine in site.
I made an investigation and found that we can use attributed strings for UILabel.
//attributes dictionary
NSDictionary *attrs =
#{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
};
NSAttributedString* attrString = [[NSAttributedString alloc] initWithData:[textString dataUsingEncoding:NSUnicodeStringEncoding]
options:attrs
documentAttributes:nil
error:nil];
Ok, now tags are enabled. But I lost my font, text looks like... default html text! That strings take their font's from css, but I receive bare strings with html tags. Just add NSFontAttributeName: [UIFont systemFontOfSize:10.f] to attrs dictionary. But without any success.
I made second try with NSMutableAttributedString:
//attributes dictionary
NSDictionary *attrs =
#{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
};
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithData:[textString dataUsingEncoding:NSUnicodeStringEncoding]
options:attrs
documentAttributes:nil
error:nil];
//and set font later
[attrString setAttributes:#{NSFontAttributeName:font} range:NSMakeRange(0, attrString.length)];
And now I've got label without any html tags, but this last step overrides all changes(bold, italic, etc.) from tags.
Question
How can we use html tags in attributed strings but set our font for them?
I am also looking for solution of this issue.
So far I Solved this by using the following code. Here I know HTML always contains Times new roman font. But If anybody find any dynamic solution please provide happily.
NSRange range = NSMakeRange(0, [parsedAttributedString length]);
[parsedAttributedString enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop)
{
UIFont* currentFont = value;
UIFont *replacementFont = nil;
if ([currentFont.fontName rangeOfString:#"BoldMT" options:NSLiteralSearch].location != NSNotFound)
{
replacementFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:14.0f];
}
else if ([currentFont.fontName rangeOfString:#"BoldItalicMT" options:NSLiteralSearch].location != NSNotFound)
{
replacementFont = [UIFont fontWithName:#"HelveticaNeue-BoldItalic" size:14.0f];
}
else if ([currentFont.fontName rangeOfString:#"ItalicMT" options:NSLiteralSearch].location != NSNotFound)
{
replacementFont = [UIFont fontWithName:#"HelveticaNeue-Italic" size:14.0f];
}
else
{
replacementFont = [UIFont fontWithName:#"HelveticaNeue-Thin" size:14.0f];
}
[parsedAttributedString addAttribute:NSFontAttributeName value:replacementFont range:range];
}];

Resources