Leo
Leo

Reputation: 1567

Auto height for label or textview within table view cell

I have a problem in an iPhone application.

Application has a table view controller with custom table view cells. Each cell has a Label (please correct me if I need to use text view etc). I am getting text dynamically from a web service call and I don't know how long text gonna be.

Now problem is that I want to adjust the table view cell height based on text I receive. How can I grow Label or TextView height withinin table view cell so it can contain all the text and in effect grow table view cell height.

Does anyone know how to handle this kind of design problem?

Thanks

Upvotes: 1

Views: 2303

Answers (2)

Suresh Varma
Suresh Varma

Reputation: 9740

You can get the height of the string passed from the below function

-(float)getHeightByWidth:(NSString*)myString:(UIFont*)mySize:(int)myWidth {

    CGSize boundingSize = CGSizeMake(myWidth, CGFLOAT_MAX);
    CGSize requiredSize = [myString sizeWithFont:mySize constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];

    return requiredSize.height;

}

Based on the above function you can set the height of the label as well as the cell where its gonna use..

Upvotes: 2

TechZen
TechZen

Reputation: 64428

The answer depends on the size and complexity of the information your displaying.

For small amounts of text, you can use the NSString UIKit Additions to calculate the dimensions of the displayed string and then adjust the size of labels or other controls of a cell before returning the cell to the tableview. This will let you fine tune the display for each cell.

For larger amounts of text I suggest a detail view if at all possible. Display a small amount of text in the table and then have the selection of the table open another view containing the full text. I think it difficult for most users to read a lot of text in a tableview.

Upvotes: 0

Related Questions