UILabel和numberOfLines和sizeToFit:

这个问题在这里已经有了答案:

  • 在UILabel 46的答案中垂直排列文本到顶部

  • 我有一个类似的问题,其中-[UILabel sizeToFit]不符合我在numberOfLines设置为2时设置的最大宽度。以下是我解决该问题的方法:

        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;
        }
    

    正如你所看到的,我也希望我的标签具有最小高度,因为-sizeToFit经常使标签变得非常小,但如果你不关心最小高度,你可以忽略这些代码。 标题MaxHeight的“幻数”为40,来自实验,发现带有这种字体的2行标签实际上只需要40px。 在这段代码中, -sizeToFit主要用于将文本保持在宽度范围内,并确定当我们有一小段文本时是否可以减少40的初始高度。


    我使用了UIFont属性lineHeight:

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

    上一篇: UILabel and numberOfLines and sizeToFit:

    下一篇: avplay stop when ts error 410