简体   繁体   English

如何在屏幕外的UITableViewCell中获取UILabel的高度?

[英]How to get the height of a UILabel within an offscreen UITableViewCell?

I am trying to make an offscreen version of a cell that will later be rendered and then use 我正在尝试制作单元格的屏幕外版本,稍后将其渲染,然后使用

[cell.label sizeToFit];

then use the new adjusted size of the label to calculate a height like this: 然后使用新调整的标签尺寸来计算高度,如下所示:

 float height = cell.complishLabel.bounds.size.height;
 return 50 + height;

However, the problem I am having is that for height I always get 0 and I am not sure why. 但是,我遇到的问题是,对于身高,我总是得到0,但我不确定为什么。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Make an off screen cell
    ZSSComplishTableViewCell *cell = [[ZSSComplishTableViewCell alloc] init];

    //Which section?
    if (indexPath.section == 0) {

        //Get a statement from the datasource and assign it to the label
        NSArray *todayComplishs = [[ZSSComplishStore sharedStore] todayComplishs];
        ZSSComplish *complish = todayComplishs[indexPath.row];
        cell.complishLabel.text = complish.statement;

        //Resize label to the amount of text
        [cell.complishLabel sizeToFit];

        NSLog(@"calculated height of label: %f", cell.complishLabel.frame.size.height);
        //Get height of label
        float height = cell.complishLabel.bounds.size.height;
        return 50 + height;
    } else if (indexPath.section == 1) {

        //Get a statement from the datasource and assign it to the label
        NSArray *tomorrowComplishs = [[ZSSComplishStore sharedStore] tomorrowComplishs];
        ZSSComplish *complish = tomorrowComplishs[indexPath.row];
        cell.complishLabel.text = complish.statement;

        //Resize label to the amount of text
        [cell.complishLabel sizeToFit];

        //Get height of label
        float height = cell.complishLabel.bounds.size.height;
        return 50 + height;
    }


    return 100;


}

This is the ZSSComplishTableViewCell.m 这是ZSSComplishTableViewCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

I think when you get 我想当你得到

NSLog(@"calculated height of label: %f", cell.complishLabel.frame.size.height);

method sizeToFit couldn't caculate complishLabel frame yet. 方法sizeToFit不能caculate complishLabel框架呢。 Try to use sizeThatFit: method instead 尝试改用sizeThatFit:方法

another way to calculate your label height 另一种计算标签高度的方法

Here's what I found worked: 这是我发现有效的方法:

//Set a random frame
CGRect labelFrame = CGRectMake(0, 0, 263, 1000);
//make a label with that frame
        UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
//set a preferredMaxLayoutWidth to what you want it constrained to
        label.preferredMaxLayoutWidth = 263;
//configure your label
        UIFont *font = [UIFont fontWithName:@"Gill Sans" size:18];
        label.font = font;
        label.lineBreakMode = NSLineBreakByWordWrapping;
        label.text = complish.statement;
//Set the number of lines to 0 so that it will use as many as the width and font says it needs
        label.numberOfLines = 0;

//resize the label
        [label sizeToFit];

//The height will now be adjusted to the amount of text 
        float height = label.frame.size.height;

        return 50 + height;

Calculating height of a UILabel is easy but also tricky. 计算UILabel的高度既简单又棘手。 There are cases to cover. 有一些案例可以解决。 I was using the code below to calculate height my project. 我正在使用下面的代码来计算项目的高度。 This will support iOS 6 and iOS 7 or above. 这将支持iOS 6和iOS 7或更高版本。 I assume you'll have multiple lines in your label. 我假设您的标签中会有多行。 Otherwise you can tweak this function to match your needs. 否则,您可以调整此功能以满足您的需求。

#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

static CGSize sizeForTextConstrainedToSize(NSString *text, UIFont *font, CGSize maxSize)
{
    if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
        CGSize size = [text sizeWithFont:font constrainedToSize:maxSize];
        return size;
    } else {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
        NSDictionary *stringAttributes = [NSDictionary dictionaryWithObjects:@[font, paragraphStyle] forKeys:@[NSFontAttributeName, NSParagraphStyleAttributeName]];
        CGRect newRect = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil];
        CGSize sizeAlignedToPixel = CGSizeMake(ceilf(newRect.size.width), ceilf(newRect.size.height));

        return sizeAlignedToPixel;
    }
}

For your code above, you shouldn't calculate the height inside the heightForRowAtIndexPath, instead calculate in advance and store it in a variable to make sure there's no lag when user scrolls the tableView. 对于上面的代码,您不应计算heightForRowAtIndexPath内部的高度,而应预先计算并将其存储在变量中,以确保用户滚动tableView时没有滞后。

OR: use estimatedHeightForRowAtIndexPath, then you can keep your code above, but return an approximated value in the estimatedHeightForRowAtIndexPath. 或者:使用estimatedHeightForRowAtIndexPath,然后可以将代码保留在上面,但是在estimatedHeightForRowAtIndexPath中返回一个近似值。

I also notice that you make use of sizeToFit to get the height, which is not right. 我还注意到您利用sizeToFit来获取高度,这是不对的。 You'll always have a boundary for whatever height you want to get. 无论您要获得什么高度,都将始终有边界。 In this case, it is the tableView's width. 在这种情况下,它是tableView的宽度。 So you have to supply a maximum CGSize every time you want get a height, which is "tableView's width x MAX_INT" 因此,每次要获取高度时,都必须提供最大CGSize,即“ tableView的宽度x MAX_INT”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM