11

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;
Oleg
  • 2,984
  • 8
  • 43
  • 71
  • This turned into quite the headache when I tried to do it. I won't post this as an answer because it's likely there's a better solution that I wasn't able to find. But, I ended up configuring all of my string's attributes programmatically (except those having to do with size) and made the label an IBOutlet, and configured "Minimum Font Size" in the "Autoshrink" drop down in the attributes inspector. – Mick MacCallum Feb 10 '13 at 14:22

1 Answers1

6

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.

Community
  • 1
  • 1
jrturton
  • 118,105
  • 32
  • 252
  • 268