Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adjustsFontSizeToFitWidth doesn't properly work

I'm developing an app for iOS > 5.0 and using Xcode 4.6.2 To explain my problem, I've a UIScrollView which contains only a bunch of UILabel. The text that i'm going to display in these UILabels are dynamic but, UILabel's frame is constant, so if current text doesn't fit in the frame width, I need to scale my font size down. So, i've found adjustsFontSizeToFitWidth property of UILabel.

Here is the explanation I took directly from UILabel class reference.

A Boolean value indicating whether the font size should be reduced in order to fit the title string into the label’s bounding rectangle.

Yeap, I thought that's what i exactly looking for since the text that i'm going to display in UILabel is always one line. So i'm aware of this property should be used with numberOfLines property to set 1.

Here is my code to make this happen.

for (NSString *currentImage in self.imagesNames)
{
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(imageNumber*resultTypeImageWidth, 10, 75, 35)];
    [lbl setFont:[UIFont fontWithName:@"GothamRounded-Bold" size:25]];
    [lbl setNumberOfLines:1];
    [lbl setText:currentImage];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl setTextColor:[UIColor colorWithHue:0.07 saturation:1 brightness:0.49 alpha:1.0]];
    [lbl adjustsFontSizeToFitWidth];
    [lbl setTextAlignment:NSTextAlignmentCenter];
    imageNumber++;
    [self.resultTypeScrollView addSubview:lbl];
}

imageNumber is a int that i'm using to place this UILabels in appropriate place in my UIScrollView which is name resultTypeScrollView. resultTypeImageWidth is a constant i've defined and set 100 to give some space between UILabels.

So, my problem is if the text doesn't fit in the label's frame, it gets truncated. I expected that if text doesn't fit the frame, font size will scale down to fit it. At least, that's what i understand from UILabel class reference. Apparently, i'm missing something, but what ?

So far,

  1. As i'm using custom font, I suspect that using custom font would be a problem. So, I changed to one of the system font, it has no effect.
  2. I tried to set NSLineBreakModeto NSLineBreakByClipping to prevent text getting truncated. After that, text doesn't get truncated but, some characters are missing which got truncated before.
  3. I've used also minimumScaleFactor to set different values to see if it has any effect, but, no effects at all.
like image 261
limon Avatar asked Jul 21 '13 19:07

limon


1 Answers

This should just work without changing many defaults. The posted code doesn't set adjustsFontSizeToFitWidth, it only gets it. Setting would look like this:

lbl.adjustsFontSizeToFitWidth = YES;
like image 178
danh Avatar answered Oct 01 '22 02:10

danh