äymm
äymm

Reputation: 411

How to fit a text with various length in a UITableViewCell?

What I have is:

I tried using an UILabel with multiple lines, set the text, and call sizeToFit. That doesn't work always, most of the time the UILabel just clips off the part of the string that doesn't fit. Also, due the varying length of the text I'd need differently sized UITableViewCells, and at the time "tableView: cellForRowAtIndexPath:" is called I don't know what the height will be.

So what I need is a non-scrolling UI element which is able to display text and resizes its height (the width should remain constant) to exactly fit the text. As mentioned the sizeToFit method produces mostly garbage.

Upvotes: 0

Views: 886

Answers (2)

Nyth
Nyth

Reputation: 582

You can use SizeWithFont: to calculate the desired height for your cell and store it in an Array so that you can return that height in HeightForRowAtIndexPath. If you need to update the text, just have a method that re-calculates the height, saves it to the array, and updates the table. Something like:

 CGSize constraintSize;
 constraintSize.width = 290.0f;
 constraintSize.height = MAXFLOAT;
 NSString *text = @"YOUR TEXT"

 CGSize theSize = [text sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

 NSLog(@"height: %f",theSize.height);

will give you the height.

Upvotes: 2

Yogev Shelly
Yogev Shelly

Reputation: 1373

This configuration should give you something simillar to what you see when you enter a loooong number in the phone app -

label.minimumFontSize = 4; //a very small font size
label.adjustsFontSizeToFitWidth = YES;
label.lineBreakMode = UILineBreakModeWordWrap;// change to what works for you
label.numberOfLines = 0;

See lineBreakMode Documentation

Upvotes: 0

Related Questions