iYousafzai
iYousafzai

Reputation: 1071

UILabel with different fonts

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?

Upvotes: 0

Views: 5233

Answers (3)

iPatel
iPatel

Reputation: 47099

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?

Upvotes: 8

Jsdodgers
Jsdodgers

Reputation: 5312

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

Upvotes: 0

Levi
Levi

Reputation: 7343

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

Upvotes: 0

Related Questions