Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios Dynamic sizing labels

I've tried to search online, but haven't found a clear answer for my issue so I've come to ask for your expert advice. I have a view with 2 labels on it. The first label is used to show an abbreviation of a name, 2-3 letters. and the second label shows the full name.

The question that I have is if there was a way to dynamically size the label based on the font type, size, and string length given? I ask because I would like the second label close to the first without too much empty space between the two or without the first label overlapping the second.

The reason that this isn't all in one label is because the first label should have a bigger font and different color scheme then the second label.

Any advice is greatly appreciated.

like image 813
Seb Avatar asked Feb 07 '12 18:02

Seb


2 Answers

You can calculate the size of in which your string will appear and then can set frame of your UILabel to that size see following code as a sample -

//Calculate the expected size based on the font and linebreak mode of your label CGSize maximumLabelSize = CGSizeMake(296,9999);  CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font                          constrainedToSize:maximumLabelSize                          lineBreakMode:yourLabel.lineBreakMode];   //adjust the label the the new height. CGRect newFrame = yourLabel.frame; newFrame.size.height = expectedLabelSize.height; yourLabel.frame = newFrame; 

Update -

Use sizeWithAttributes: instead, which now takes an NSDictionary. Pass in the pair with key UITextAttributeFont and your font object like this:

CGSize size = [string sizeWithAttributes:                        @{NSFontAttributeName:                          [UIFont systemFontOfSize:17.0f]}]; 

Check Replacement for deprecated sizeWithFont: in iOS 7? for more details

like image 96
Saurabh Avatar answered Sep 16 '22 16:09

Saurabh


This will also do the trick and will take into account attributed text

label.attributedText = attrString; CGSize maximumLabelSize = CGSizeMake(187,CGFLOAT_MAX); CGSize requiredSize = [label sizeThatFits:maximumLabelSize]; CGRect labelFrame = label.frame; labelFrame.size.height = requiredSize.height; label.frame = labelFrame; 
like image 43
noRema Avatar answered Sep 16 '22 16:09

noRema