Setting custom font in UITextView with attributed string - ios

I have a UITextView which contains an attributed string configured through storyboard. Now i want a custom font to be applied. I am doing it through code
textView.font = [UIFont fontWithName:kCustomFont size:textView.font.pointSize];
The problem is fonts get changed losing all the attributes. How do i fix it?
(Working on iOS 5 and above)

What's in your kCustomFont? If the FontName is wrong, even a single Character, the standard SystemFont will be used.

You should change it via NSMutableAttributedString's attributes.
I.e. use something like:
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithAttributedString:textView.text];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
[mutableSrting addAttributes:attrs range:NSMakeRange(0, [mutableString length])];
textView.attributedText = mutableString;
[mutableString release];

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;

NSMutableAttributedString doesn't show string in different color for some specific range in iOS 8 & iOS 9

I am using attributes string in my code. To set font & color of text for some specific range.
For this I am using below code.
Font is working for range but color is not set for that range. There may be some issue in NSForegroundColorAttributeName.
Please let me know if anyone have solution.
NSDictionary *attrs = #{ NSFontAttributeName:[UIFont systemFontOfSize:12.0f],NSForegroundColorAttributeName : [UIColor redColor] };
NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc]initWithString:#"New Message from Test"];
[titleStr addAttributes:attrs range:NSMakeRange(0, 3)];
I also faced the similar problem. So I passed my string as HTML string and got it done like this.
NSString *name = #"<center><font color='#cd1c5f' size='4px'>"
#"New"
#"</font>"
#"<font color='#000000' size='4px'>"
#"Message from test"
#"</font></center>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[name dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
_lbl_nm.attributedText=attrStr;
You can append two attribute string with different attributes of red colour & text colour. Lets try using the following code chunk.
NSDictionary *attrs = #{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:12.0]};
NSMutableAttributedString *titleString = [[[NSMutableAttributedString alloc] initWithString:#"New" attributes:attrDict] autorelease];
attrs = #{NSForegroundColorAttributeName:[UIColor lightTextColor], NSFontAttributeName:[UIFont systemFontOfSize:12.0]};
NSAttributedString *messageString = [[[NSAttributedString alloc] initWithString:#" Message from Test" attributes:attrs] autorelease];
[titleString appendAttributedString:messageString];
[self.titleTextView setAttributedText:titleString];
Check if you are changing the textcolor of the label after you set the attributed title. Thats the only way you will face this problem. Do it before you set the title.
cell.textLabel.textColor = [UIColor grayColor];
cell.textLabel.attributedText = titleStr;
I don't see any problems with your code. I just copied your code and tested, everything's fine.

NSMutableAttributedString Crashing App

I'm doing something wrong with the range (I think) in setting this NSMutableAttributedString. Can anyone tell me why this is crashing my program? It looks right to me, but I'm obviously wrong! Thanks.
NSString *placeHolderString = #"USERNAME";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
float spacing = 5.0f;
// crashes on this line
[attributedString addAttribute:NSKernAttributeName
value:#(spacing)
range:NSMakeRange(0, [placeHolderString length])];
self.userNameTextField.attributedPlaceholder = attributedString;
What I think was causing your issue is that you were never really accounting for your placeholderString in the first place. In addition, your value parameter could simply use numberWithFloat as the application would then known what type you are using all the time.
Once you account for the placeHolderString, you are then going to use the length for the attributeString, as it now just contains the contents of your placeholderString. Then we just simply copy that string which contains your attribute using the UITextField property attributedText.
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:placeHolderString];
float spacing = 5.0f;
[attributeString addAttribute:NSKernAttributeName
value:[NSNumber numberWithFloat:spacing]
range:(NSRange){0,[attributeString length]}];
userNameTextField.attributedText = [attributeString copy];
For more context, attributes like NSUnderlineStyleAttributeName exist and you can do some really powerful things with NSMutableAttributedString. Refer to the documentation for options.

How can I show the text with different fonts in textView in ios?

Hi I am doing one application. In that I need to show text in different fonts. I mean if I show name in one font and I show city name in different font.
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 100)];
textView.text = #"Vijay Apple Dev";
NSString *textViewText = textView.text;
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:textViewText];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Courier" size:20]
range:[textViewText rangeOfString:#"Apple"]];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Verdana" size:20]
range:[textViewText rangeOfString:#"Vijay"]];
textView.attributedText = attributedText;
[self.view addSubview:textView];
Try to do like this one... And customize according to your requirement like font name and font size
NSString *firstName = #"FirstName";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:firstName];
UIFont *font = [UIFont fontWithName:#"Helvetica" size:20];
[attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, firstName.length)];// Here define your range.
textView.attributedText = attributedString;
//Use attributed String
//Apply properties to both strings
//then merge and set it to textview
NSString *selectedString=#"Hey,";
UIFont *fontSelectedText = [UIFont boldSystemFontOfSize:25];
NSDictionary *dictBoldSelectedText = [NSDictionary dictionaryWithObjectsAndKeys:fontSelectedText, NSFontAttributeName, nil];
NSMutableAttributedString *mutAttrTextViewSelectedString = [[NSMutableAttributedString alloc] initWithString:selectedString];
[mutAttrTextViewSelectedString setAttributes:dictBoldSelectedText range:NSMakeRange(0,selectedString.length)];
[_tTextView setAttributedText:mutAttrTextViewSelectedString];
//Second String
NSString *restOfStrig=#"\nHello";
NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:restOfStrig];
UIFont *fontText = [UIFont boldSystemFontOfSize:16];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[mutAttrTextViewString setAttributes:dictBoldText range:NSMakeRange(0,restOfStrig.length)];
//Combining both the Attributed String
[mutAttrTextViewSelectedString appendAttributedString:mutAttrTextViewString];
NSMutableAttributedString * finalAttributedStr=[[NSMutableAttributedString alloc] initWithAttributedString:mutAttrTextViewSelectedString];
//setting it to the textView
[_tTextView setAttributedText:finalAttributedStr];
Use NSAttributedString
An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. The cluster’s two public classes, NSAttributedString and NSMutableAttributedString, declare the programmatic interface for read-only attributed strings and modifiable attributed strings, respectively.
NSAttributedString
When you create your attributed string, then just set it to your textView:
self.textView.attributedText = myAttributedString;

Replace the truncation ellipsis of UILabel in iOS 7

How can I replace the truncation ellipsis ("…") of a UILabel in iOS 7 with another attributed character? For example, with a colored ">".
I was hoping Text Kit's NSLayoutManager would make this possible, but it appears UILabel doesn't make it public if it uses it.
Also, can I safely assume that an ellipsis is used as the truncation character in every localisation? Maybe different languages have different truncation characters.
I recommend you use TTTAttributedLabel, just set property "attributedTruncationToken" to your custom string.
I don't think it gives you access to this. I think you would have do handle it manually. For example, use TextKit to determine the size of your string, if it doesn't fit in the available area, truncate it yourself and append a ">" and then put your new string in the label.
NSAttributedString has methods for getting the size of the string.
Let me know if you need any more detail on this..?
I think you can do some customization in -replaceElipsesForLabel method provided by Fonix to get your desired result.
I have written a method to do it, and works in iOS7
-(void)setCustomEllipsis:(NSString*)customEllipsis inLabel:(UILabel*)label with:(NSString*)string{
//Replace the ellipsis
NSMutableString* result = [[NSMutableString alloc] initWithString:#""];
NSArray* strings = [string componentsSeparatedByString:#" "];
for (NSString* s in strings) {
CGRect newSize = [[NSString stringWithFormat:#"%#%#%#",result,s,customEllipsis] boundingRectWithSize:CGSizeMake(label.frame.size.width,0) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:label.font} context:nil];
if (newSize.size.height < label.frame.size.height) {
[result appendString:s];
[result appendString:#" "];
}else{
[result appendString:customEllipsis];
break;
}
}
[label setText:result];
//Set different font to the ellipsis
const CGFloat fontSize = 13;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
UIColor *foregroundColor = [UIColor lightGrayColor];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:regularFont, NSFontAttributeName,foregroundColor, NSForegroundColorAttributeName, nil];
NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:boldFont, NSFontAttributeName, nil];
const NSRange range = [label.text rangeOfString:customEllipsis];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:result
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
[label setAttributedText:attributedText];
}

Resources