UILabel的尺寸是否会恢复其高度?

时间:2013-02-25 14:19:57

标签: iphone ios objective-c cocoa-touch uilabel

我正在尝试在我的应用中实现以下内容:

themeLabel = [[UILabel alloc] init];
themeLabel.backgroundColor = [UIColor redColor];
themeLabel.text = themeString;
[themeLabel sizeThatFits:CGSizeMake(274, 274)];
themeLabel.numberOfLines = 0;
[topThemeView addSubview:themeLabel];

NSLog(@"Height is %f ", themeLabel.frame.size.height);

[themeLabel setFrame:CGRectMake(leftMargin, mainScrollView.frame.origin.y + topPadding, 274, themeLabel.frame.size.height)];

我最终得到的Label's高度为0.0。有什么想法吗?

3 个答案:

答案 0 :(得分:4)

themeLabel = [[UILabel alloc] init];
themeLabel.backgroundColor = [UIColor redColor];
themeLabel.text = themeString;
themeLabel.numberOfLines = 0;

CGRect labelFrame = CGRectMake(leftMargin, mainScrollView.frame.origin.y + topPadding, 0.0, 0.0);
labelFrame.size = [themeLabel sizeThatFits:CGSizeMake(274, 274)];

[themeLabel setFrame:labelFrame];
[topThemeView addSubview:themeLabel];

答案 1 :(得分:3)

sizeThatFits要求视图计算并返回最适合其子视图的大小。所以你永远不会设置themeLabel的框架

你应该这样做:

themeLabel.numberOfLines = 0;
CGSize size = [themeLabel sizeThatFits:CGSizeMake(274, 274)];
themeLabel.frame = (CGRect) {0,0, size};

答案 2 :(得分:2)

我为UILabels创建了一个处理高度的类别:

<强>的UILabel + TCFlexibleHeight.h

#import <UIKit/UIKit.h>

@interface UILabel (TCFlexibleHeight)

- (CGFloat)heightForText:(NSString*)text;
- (CGFloat)heightForCurrentText;
- (CGFloat)adjustHeightForCurrentText;

@end

<强>的UILabel + TCFlexibleHeight.m

#import "UILabel+TCFlexibleHeight.h"

static const NSInteger kMaxLines = 1000;

@implementation UILabel (TCFlexibleHeight)

- (CGFloat)heightForText:(NSString*)text {
    if (text == nil) {
        return 0;
    }

    NSInteger numberOfLines = self.numberOfLines > 0 ? self.numberOfLines : kMaxLines;
    CGSize size = CGSizeMake(self.frame.size.width, self.font.lineHeight * numberOfLines);
    return [text sizeWithFont:self.font constrainedToSize:size lineBreakMode:self.lineBreakMode].height;
}

- (CGFloat)heightForCurrentText {
    return [self heightForText:self.text];
}

- (CGFloat)adjustHeightForCurrentText {
    CGFloat height = [self heightForCurrentText];
    CGRect frame = self.frame;
    frame.size.height = height;
    return height;
}

@end

使用此类别,您的代码将是这样的:

[themeLabel setFrame:CGRectMake(leftMargin, mainScrollView.frame.origin.y + topPadding, 274, [themeLabel heightForCurrentText])];

请注意,此类别不处理属性字符串,并要求换行设置为剪辑为字符。