简体   繁体   中英

Vary table view cell height based on text

I have a table view with a few cells. The text that fills up the cell is unpredictable (based on the result of an API request). What I want to do is adjust the cell's height based on if the cell's text is too lengthy for the cell (eg the cell adds '...' to the text).

That way whatever the result/text and gets presented into a table view cell is always fully shown.

I would prefer not to implement the heightForRowAtIndexPath because I would have to implement a lot of code to do so.

UPDATE:

When I say "I have a lot of code to do so", I mean I literally have a lot of code parsing out requests and checking for conditions and performing algorithms and plus I have many table views. Just moved that stuff to another method and Im off to go!

Could you point me to any resources demoing this, do you know how to do this?

You must implement heightForRowAtIndexPath to vary the height of your table rows, but there isn't necessarily alot of code needed to calculate the height.

Use NSString:sizeWithFont:constrainedToSize to calculate the cell size needed.

    //szMaxCell contains the width of your table cell, and the maximum height you want to allow
// strCellContents is an NSString containing the text to display

        CGSize szMaxCell = CGSizeMake (tableView.frame.size.width - 20,999);
        UIFont *font = [UIFont systemFontOfSize:12];    // whatever font you're using to display
        CGSize szCell = [strCellContents sizeWithFont:font constrainedToSize:szMaxCell lineBreakMode:UILineBreakModeWordWrap];

szCell contains the size of the label. You'll use this size both to calculate the frame of your UILabel in your cellForRowAtIndexPath, as well as in your heightForRowAtIndexPath.

Use heightForRowAtIndexPath . It shouldn't be lots of extra code. Just get a reference to the object you are populating your cell with, check out the length of that text value and return the height you need. That is exactly what that delegate method is designed for.

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