0

I'm developing an iPhone app with latest SDK and XCode 4.2

I'm using this code to align vertically a text set it previously in an UILabel. Here is the code:

- (void)resizeLabel:(UILabel *)label
{
    CGSize maximumLabelSize = label.frame.size;

    CGSize expectedLabelSize = [label.text sizeWithFont:label.font 
                                      constrainedToSize:maximumLabelSize 
                                          lineBreakMode:label.lineBreakMode]; 

    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    NSLog(@"NumLines: %d, OldWidth: %f, NewWidth: %f, OldHeight: %f, newHeight: %f", label.numberOfLines, maximumLabelSize.width,  expectedLabelSize.width, maximumLabelSize.height, expectedLabelSize.height);
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;
}

For text: "Iglesia de la Merced" I get:

NumLines: 2, OldWidth: 205.000000, NewWidth: 153.000000, OldHeight: 39.000000, newHeight: 21.000000

For text: "Antiguo convento de los merdarios" I get

NumLines: 2, OldWidth: 205.000000, NewWidth: 187.000000, OldHeight: 39.000000, newHeight: 42.000000


Both are set up to use two lines but text is always drawn in one line only.

Why am I getting double height when expectedLabelSize.width is smaller than maximumLabelSize.width?

VansFannel
  • 45,055
  • 107
  • 359
  • 626

1 Answers1

1

It is wrapping in two lines, I guess.

from the doc:

This method computes the metrics needed to draw the specified string. This method lays out the receiver’s text and attempts to make it fit the specified size using the specified font and line break options. During layout, the method may break the text onto multiple lines to make it fit better. If the receiver’s text does not completely fit in the specified size, it lays out as much of the text as possible and truncates it (for layout purposes only) according to the specified line break mode. It then returns the size of the resulting truncated string. If the height specified in the size parameter is less than a single line of text, this method may return a height value that is bigger than the one specified.

Something to mention:
if you set numberOfLines to 0, it will automatically use as many lines as possible and needed.

Also try:

myUILabel.numberOfLines = 0;
myUILabel.text = @"Antiguo convento de los merdarios";
[myUILabel sizeToFit];
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178