UILabel and numberOfLines and sizeToFit:

This question already has an answer here:

  • Vertically align text to top within a UILabel 46 answers

  • I had a similar problem where -[UILabel sizeToFit] was not respecting the max width I set when numberOfLines was set to 2. Here's how I solved that problem:

        CGFloat titleMaxWidth = 200;
        CGFloat titleMinHeight = 30;
        CGFloat titleMaxHeight = 40;
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, titleMaxWidth, titleMaxHeight)]; // alternatively, you could do this in a nib
        titleLabel.numberOfLines = 0;
        titleLabel.text = @"The title label will be sized appropriately with this technique.";
        titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [titleLabel sizeToFit];
        titleLabel.numberOfLines = 2;
        if (titleLabel.height > titleMaxHeight)
        {
            titleLabel.height = titleMaxHeight;
        }
        else if (titleLabel.height < titleMinHeight)
        {
            titleLabel.height = titleMinHeight;
        }
    

    As you can see, I also wanted a minimum height for my label, as -sizeToFit often makes the label really small, but you could disregard that code if you don't care about a minimum height. The "magic number" of 40 for the titleMaxHeight comes from experimentation and finding out that a 2 line label with this font really only needs 40px. In this code, -sizeToFit is mainly used to keep the text within the width and determine whether the initial height of 40 can be reduced when we have a short string of text.


    我使用了UIFont属性lineHeight:

    CGFloat labelHeight = label.font.lineHeight*label.numberOfLines;
    
    链接地址: http://www.djcxy.com/p/28180.html

    上一篇: UILabel sizeToFit不适用于自动布局ios6

    下一篇: UILabel和numberOfLines和sizeToFit: