6

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

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。任何想法为什么?

4

3 回答 3

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];
于 2013-02-25T14:30:38.853 回答
3

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

你应该做:

themeLabel.numberOfLines = 0;
CGSize size = [themeLabel sizeThatFits:CGSizeMake(274, 274)];
themeLabel.frame = (CGRect) {0,0, size};
于 2013-02-25T14:29:44.843 回答
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])];

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

于 2013-02-25T14:38:36.913 回答