简体   繁体   中英

ios7 storyboard dynamic UITableView cell height based on label content

I am attempting to implement dynamic UITableViewCell heights based on the content of certain label in the cell. The cell has a few other UI objects added to it (an image view, a few static labels etc) and I have set constraints for everything. Only one label needs to be sized dynamically.

Im using this method to find the size of the text:

-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth
{
    CGSize maximumSize = CGSizeMake(labelWidth, 10000);

    UIFont *systemFont = [UIFont systemFontOfSize:15.0];
                               lineBreakMode:NSLineBreakByWordWrapping];

    CGSize labelSize = [text boundingRectWithSize:maximumSize options: NSStringDrawingUsesLineFragmentOrigin
                                       attributes: @{ NSFontAttributeName: systemFont } context: nil].size;
    return labelSize.height;
}

im sure there is a better way to do that, but it works for now.

in cellForRowAtIndexPath im resizing the label to be able to hold the text and setting the appropriate attributes:

UILabel *reviewLabel = (UILabel *)[cell viewWithTag:102];

    //280 is the width of the label
    reviewLabel.preferredMaxLayoutWidth = 280;

    CGFloat reviewLabelHeight = [self getLabelHeightForText:reviewText andWidth:reviewLabel.frame.size.width];

    reviewLabel.frame = CGRectMake(reviewLabel.frame.origin.x, reviewLabel.frame.origin.y, reviewLabel.frame.size.width, reviewLabelHeight);

    reviewLabel.text = reviewText;

    reviewLabel.numberOfLines = 0;

    reviewLabel.lineBreakMode = NSLineBreakByWordWrapping;

and that works fine, but im having trouble resizing the actual cell height. right now I have

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

NSString *reviewText = [review objectForKey:@"reviewText"];

//280 is the width of the review label
CGFloat textHeight = [self getLabelHeightForText:reviewText andWidth:280]; 
}

but im not sure how to resize the cell using that text height. The cells are normally 91 px high if the text length is small enough to not need to be resized. So Ive got to return 91 if the cell doesnt need to be resized, or if it does need resizing return the text height + enough pixels to fit all the other objects in the cell? Im very confused as to how to resize the cell. The label is resizing fine, but cant get the cell figured out.

As you are using ios7+, try

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath

instead of tableView:heightForRowAtIndexPath .

And return a CGFloat with the height offset that you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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