UILabel with different fonts - ios

I have this string that I want to display in a label:
NSString *criticsScore=[NSString stringWithFormat:#"%#\%%",[dict objectForKey:#"critics_score"]];
_criticRating.text=criticsScore;
I want to set a small font for \%% and a large font for [dict objectForKey:#"critics_score"]];
Is this possible?

You Need to use your own control for drawing an NSAttributedString, like TTTAttributedLabel.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"Blah1:blah-blah%d. Blah2:-%d%%", [currentCoupon.couponPrice intValue],[currentCoupon.couponDiscountPercent intValue]];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(0,30)];/// Define Range here and also BackGround color which you want
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,30)];/// Define Range here and also TextColor color which you want
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];
lblWithText.attributedText = str;
Above Code I got From How to use multiple font stylings on a single string inside a label?

Read this post. It is about NSAttributedStrings. I think that is what you need.

You would have to do it with two UILabels. You would set the first label to be all of the text excpt the \%%, and get the size of that label using sizeWithFont: on the text that goes in that label. Then set the second label to start at the end of that label's frame.
So, it would look something like this, changing the coordinates based on where you want the labels:
NSString *criticsScore = [NSString stringWithFormat:#"%#",[dict objectForKey:#"critics_score"]];
NSString *str2 = #"\%%";
UIFont *criticsFont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
UIFont *font2 = [UIFont systemFontOfSize:12.0];
//Get the sizes of each text string based on their font sizes.
CGSize criticsSize = [criticsScore sizeWithFont:criticsFont];
CGSize size2 = [str2 sizeWithFont:font2];
int x = 0;
int y = 0;
//The first label will start at whatever x and y are.
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(x,y,criticsSize.width,criticsSize.height)];
[label1 setFont:criticsFont];
//Create a second label with the x starting at x+criticsSize.width;
//The y will start at y+criticsSize.height-size2.height, so that it will be aligned with the bottom.
//Change these to align it differently.
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(x+criticsSize.width,y+criticsSize.height-size2.height,size2.width,size2.height)];
[label2 setFont:font2];
[self.view addSubview:label1];
[self.view addSubview:label2];

Related

Calculate height and number of lines of the label

I have a text that is shown in a UILabel. However, this text have several line spaces as shown below. Now, I want to calculate the height of this label, considering the newline, Bold-text and font size. Since this text can not be placed in a Single line in the label, there might be several lines that we must determine at runtime. Based on this height I want to increase the y cordinate of my UILabel so the UILabel will always be stuck to the bottom of the screen. (Only the height will increase (upwards))
How can I solve this?
NSAttributedString *linespace = [[NSAttributedString alloc] initWithString: #"\n"];
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:#"Mathews is a " attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:40]}];
NSAttributedString* attributed = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:#"%#", #"Bad guy"] attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:40]}];
[mutableString appendAttributedString: linespace];
[mutableString appendAttributedString: attributed];
[mutableString appendAttributedString: linespace];
You can get height by
CGRect rectCountry = [mutableString boundingRectWithSize:(CGSize){#“YOUR WIDTH”, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize sizeCountry = rectCountry.size;

How to set correctly the line height of UILabel with an AttributedString?

I have a UILabel which uses an Attributed String. I want to have its line height to be exactly the size of the font size, not a pixel bigger. However, a top and bottom padding are being added. See image below:
This is my code to create the label.
NSDictionary *basicAttributes = #{NSForegroundColorAttributeName: [UIColor whiteColor], NSBackgroundColorAttributeName: [UIColor blueColor]};
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:basicAttributes];
UIFont *font = [UIFont fontWithName:#"AvenirNext-Regular" size:20.0];
[attributes setObject:font forKey:NSFontAttributeName];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple = 1.0f;
[attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
self.helloWorldLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:#"Hola" attributes:attributes];
Attempts
I have tried to call sizeToFit after setting the attributedText without success.
[self.helloWorldLabel sizeToFit];
I have played with other attributes of NSMutableParagraphStyle such as lineSpacing without success.
paragraphStyle.lineSpacing = 0.0f;
What am I missing?
Thanks in advanced
It sounds like you want to use boundingRectWithSize: Here's a short example of how to use it. This code will dynamically determine your label size based on the text in your label. Setting the constraining sizes allows a max size if content needs to overflow to multiple lines.
NSString *text = [NSString stringWithFormat:#"Title Header:%#", value];
NSRange boldRange = [text rangeOfString:#"Title Header:"];
NSRange normalRange = [text rangeOfString:value];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
//Add attributes for appropriate ranges
[attributedText setAttributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13.0f]} range:boldRange];
[attributedText setAttributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue" size:13.0f]} range:normalRange];
//Determine rect for attributed text constrained within max values
CGRect textAttributedSize = [attributedText boundingRectWithSize:CGSizeMake(CellTitleWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:NULL];
[self.myLabel setText:attributedText];
[self.myLabel setFrame:textAttributedSize];
Check this link. There is no 100% way to correctly set the frame to fit the letters. You can calculate the attributed string with CoreText like using CTFramesetterRef CTFramesetterSuggestFrameSizeWithConstraints but it is more additional work.

Setting attributedText of UILabel causing issue with Lengthier content

In my project I want to add an attributed text in UILabel placed on the xib.
It's working perfectly, but if large text appears it shows some issues.
My current implementation:
- (void)viewDidLoad
{
[super viewDidLoad];
_demoLabel.numberOfLines = 0;
_demoLabel.lineBreakMode = NSLineBreakByWordWrapping;
_demoLabel.attributedText = [self demoNameWithFontSize:21 andColor:[UIColor redColor]];
}
- (NSMutableAttributedString *)demoNameWithFontSize:(CGFloat)fontSize andColor:(UIColor *)color
{
NSMutableAttributedString *attributedText = nil;
NSString *demoName = #"Blah blah blah";
UIFont *demoFont = [UIFont fontWithName:#"Zapfino" size:fontSize];
attributedText = [[NSMutableAttributedString alloc] initWithString:demoName];
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineBreakMode = NSLineBreakByWordWrapping;
[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, [demoName length])];
[attributedText addAttribute:NSFontAttributeName value:demoFont range:NSMakeRange(0, [demoName length])];
[attributedText addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, [demoName length])];
return attributedText;
}
Output:
Issue:
It is not displaying the whole text, even if I applied the NSMutableParagraphStyle.
How can I solve this ?
Alternative I found:
If I change
UIFont *demoFont = [UIFont fontWithName:#"Zapfino" size:fontSize];
to
UIFont *demoFont = [UIFont systemFontOfSize:fontSize];
It'll work and gives output like:
But the issue is I need to use custom font, can't use default font. Also cannot change the font size.
I checked UILabel class reference and googled, but couldn't find a solution. Please help me.
Is there anyway to span this text into multiple lines ?
You need to resize the UILabel to fit the text.
You can calculate the size with the boundingRectWithSize:options:context: NSAttributedString class method, which takes an attributed string and calculates the size within a set rect based on all the attributes of the string.

How can I set the color and alignment of attributed text in a UITextView in iOS 7?

The formatting of my textViews worked fine in iOS 6, but no longer in iOS 7. I understand with Text Kit much of the under the hood stuff has changed. It's become really quite confusing, and I'm hoping someone can help straighten it out a bit by helping me with something as simple as this.
My static UITextView originally was assigned a value for it's textColor and textAlignment properties. Then I made a NSMutableAttributedString, assigned it an attributes, then assigned it to the textView's attributedText property. The alignment and color no longer take effect in iOS 7.
How can I fix this? If these properties take no effect, than why do they exist anymore? Here's the creation of the textView:
UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];
NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:#"Welcome"];
UIFont *font = [UIFont fontWithName:#"Avenir-Light" size:60];
[title addAttribute:NSParagraphStyleAttributeName value:font range:NSMakeRange(0, title.length)];
titleView.attributedText = title;
[self.view addSubview:titleView];
Curious, the properties are taken into account for UILabel but not for UITextView
Why don't you just add attributes for color and alignment to the attributed string similar to the way you are doing with the font?
Something like:
NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:#"Welcome"];
UIFont *font = [UIFont fontWithName:#"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];
//add color
[title addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, title.length)];
//add alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[title addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, title.length)];
titleView.attributedText = title;
Edit: Assign the text first, then change the properties and this way it works.
UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];
//create attributed string and change font
NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:#"Welcome"];
UIFont *font = [UIFont fontWithName:#"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];
//assign text first, then customize properties
titleView.attributedText = title;
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];

How to setup multi-segment text to look like a single sentence in iOS?

I have a line of text that needs to be displayed in UITableViewCell. The text consists of multiple sections coming from the database. Each section has a different color. E.g:
Lorem ipsum dolar sit amet
Each item comes from the database and is a different color.
I am trying to setup five UITextFields (one for each.)
So far so good.
How do I make it look like a single string to make sure inter-word spacing is same.
With the NSMutableAttributedString, you could do it like so:
NSArray *words = #[#"Lorem ", #"ipsum ", #"do", #"lar si", #"t amet"];
NSArray *colors = #[[UIColor blueColor], [UIColor greenColor], [UIColor yellowColor], [UIColor redColor], [UIColor blackColor]];
// Concatenate the list of words
NSMutableString *string = [NSMutableString string];
for (NSString *word in words)
[string appendString: word];
// Add the coloring attributes
NSMutableAttributedString *attrString = [[[NSMutableAttributedString alloc] initWithString: string] autorelease];
int location = 0;
for (int i = 0; i < words.count; i++) {
NSString *s = [words objectAtIndex: i];
[attrString addAttribute: NSForegroundColorAttributeName
value: [colors objectAtIndex: i]
range: NSMakeRange(location, s.length)];
location += s.length;
}
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(20, 20, 280, 21)];
[label setAttributedText: attrString];
[self.view addSubview: label];
[label release];
You can do this with
UIWebView with formatted HTML Text
UILabel by measuring the text with [NSString sizeWithFont:] and positioning and sizing the label (would also go with UITextField considering the padding)
NSMutableAttributedString as mentioned by Jason Barker
After setting up the text fields, you can use the method
[yourTextField sizeToFit];
This will make the textfields enclose the length of the word.
Afterwards, you can place these text fields one after the other giving enough space in between to look like a normal sentence.
Place the UITextFields in an NSArray (in order).
In the cellForRowatIndexPath delegate method-
int x = 0; //or wherever you want the string to start from
for (UITextField *textField in arrTextFields)
{
textField.frame = CGRectOffset(textField.bounds, x, 0);
[cell addSubview:textField];
x += textField.frame.size.width + 2; //Adjust the constant to set spacing
}

Resources