0
votes

I have a UIlabel with constraints set. Constraint to both left and right sides and vertical center were set to the label. The parent view width is dynamic, means can be wider or not but the height is static. The label will be set with some text that are long or short. I also set the minimum font size so that the font would not wrap and set it to one line only. Since I set the minimum font size, the text height auto adjusts to fit the text but the problem the text is not centered vertically instead it sits at the bottom of the UIlabel. I tried to resize the height of the UIlabel but I can't get it to resize with the right size based on the new font size and when to set the new size. I tried the solutions here by getting the font size and setting the height dynamically instead it caused unexpected results. I am running it on iOS 6.

1

1 Answers

0
votes

I figured it out myself. Below is a sample code

+(void)autoFontResizeLabel:(UILabel*)label inView:(UIView*)containerView{

     NSString *text = label.text;
     //determine the font size
    CGFloat actualFontSize;
    [text sizeWithFont:label.font
             minFontSize:18
          actualFontSize:&actualFontSize
                forWidth:label.bounds.size.width
           lineBreakMode:label.lineBreakMode];

    //reset the label content and frame
    [label setText:@""];
    [label setText:text];
    //turn off auto adjust to allow new text with correct font
    label.adjustsFontSizeToFitWidth = NO;

    [label setFont:[UIFont fontWithName:@"HelveticaNeue" size:actualFontSize]];
    //optional
    [label sizeToFit];
    CGSize barSize = containerView.frame.size;

    CGFloat titleY = fabsf(barSize.height - label.frame.size.height)/2;
    [label setFrame:CGRectMake(label.frame.origin.x, titleY, label.frame.size.width,     label.frame.size.height)];
}