I want to resize cell's height according to the label's height and label's height according to text. Or is there any way I can resize the cell's height according to the text entered in UITextView
?
Asked
Active
Viewed 1.8k times
15

Stonz2
- 6,306
- 4
- 44
- 64

Rahul Vyas
- 28,260
- 49
- 182
- 256
-
Are you saying you want to resize a UITableViewCell containing a UITextView as more text is entered into the text view? – teabot Jun 18 '09 at 12:47
-
no sir i have a custom cell with label on the cell.and text is coming from the database. how do i increase cell row height and label no of lines or label height so that long text can be fitted into cell's label – Rahul Vyas Jun 21 '09 at 06:22
-
possible duplicate of [Variable UITableCellView height with subview](http://stackoverflow.com/questions/128012/variable-uitablecellview-height-with-subview) – outis Jul 14 '12 at 20:28
2 Answers
17
THIS METHOD IS DEPRECATED SINCE iOS 7.0.
There is a UITableView
delegate method called heightForRowAtIndexPath
that is called before you create a cell or a table.
You could use the NSIndexPath
passed to it to get the text at a specific row and use the sizeWithFont
method from UIStringDrawing.h
to compute a CGSize
for that row.
For example:
CGSize size = [text sizeWithFont:font
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeWordWrap];
And finally you would return size.height
.

Vyacheslav
- 26,359
- 19
- 112
- 194

Josh Vera
- 650
- 7
- 11
6
--For iOS7--
Basing this off of Josh Vera's answer … place this in heightForRowAtIndexPath.
I have my table data stored in an NSArray *tableData.
// set the desired width of the textbox that will be holding the adjusted text, (for clarity only, set as property or ivar)
CGFloat widthOfMyTexbox = 250.0;
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Get a reference to your string to base the cell size on.
NSString *cellText = [self.tableData objectAtIndex:indexPath.row];
//set the desired size of your textbox
CGSize constraint = CGSizeMake(widthOfMyTextBox, MAXFLOAT);
//set your text attribute dictionary
NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0] forKey:NSFontAttributeName];
//get the size of the text box
CGRect textsize = [cellText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
//calculate your size
float textHeight = textsize.size.height +20;
//I have mine set for a minimum size
textHeight = (textHeight < 50.0) ? 50.0 : textHeight;
return textHeight;
}
I haven't tested it for iOS<7, but I believe it should work for that as well.

digitalHound
- 4,384
- 27
- 27
-
-
Scratcha see updated answer. It's the width that you want your textbox to be. – digitalHound Feb 03 '15 at 19:00