Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Auto-shrink UILabel with Attributed text

I have UILabel which contains two attributed strings separated by a new line. FIrst string has font size set to 17 and the second one to 14. I want my first NSMutableAttributedString be resized to minimum font size if its content can't fit in a single line.

Is that possible?

It is pretty simple to configure such UILabel behaviour by setting "auto shrink to minimum font size" in IB for plain text, but don't know how to do it for attributed text.

Here is my code:

NSString *eventName = @"Looong Event Name";
NSString *placeString = @"My place";

eventName = [eventName stringByAppendingString:@"\n"];        
NSMutableAttributedString *attrName = [[NSMutableAttributedString alloc] initWithString:eventName];
[attrName addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(0, [eventName length])];


 NSMutableAttributedString *attrPlace = [[NSMutableAttributedString alloc] initWithString:placeString];
 [attrPlace addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, placeString.length)];
 [attrPlace addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, placeString.length)];

  NSMutableAttributedString *finalString = [[NSMutableAttributedString alloc] initWithAttributedString:attrName];
  [finalString appendAttributedString:attrPlace];

  UILabel *nameLabel = (UILabel *)[cell viewWithTag:100];

  nameLabel.attributedText = finalString;
like image 530
Oleg Avatar asked Feb 10 '13 13:02

Oleg


1 Answers

I guess this is a follow on from your earlier question.

I don't think you can do this automatically, but there is a size method of NSAttributedString which you can use to check if your string is too big, and adjust yourself if required.

like image 168
jrturton Avatar answered Nov 19 '22 04:11

jrturton