Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UITableView Dynamic Cell Height

I have search and searched through endless blogs and articles on how to determine a dynamic height for a custom UITableViewCell and its detailed text. I have really had a hard time finding any good documentation on this.

What I need to do is have the cell grow according to the the text inside but never go below a height of 70.

I have tried several of the answers for this type of question here on StackOverflow but none of them worked. My whole app is just about finished but I really need to get this accomplished before I release and its troublesome.

Here is what I am trying but I just get a slop of cells overlapping each other. From what I read I need to find the frame if the custom cell or textview in the cell as well but I am not sure how to do that or mix them all together to return one height.

Any Help would be greatly appreciated Thank you!

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

  CGSize aSize;
aSize = [[(Tweet*)[tweets objectAtIndex:indexPath.row]tweet] sizeWithFont:[UIFont 
systemFontOfSize:14]
            constrainedToSize:CGSizeMake(300.0, 1000.0)
                lineBreakMode:UILineBreakModeTailTruncation];

return  aSize.height;
}
like image 430
FreeAppl3 Avatar asked Sep 28 '11 20:09

FreeAppl3


2 Answers

I had a similar issue a while back and this helped me tremendously.

#define PADDING 10.0f
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = [self.items objectAtIndex:indexPath.row];
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];

    return textSize.height + PADDING * 3;
}
like image 187
WrightsCS Avatar answered Sep 20 '22 20:09

WrightsCS


Hey there so you are going to need to store the list of strings in an NSArray and then you are going to need to calculate the height of the nsstring using sizeWithFont:constrainedToSize: the documentation is found here http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html

so your tableView method should look something like

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:"Helvetica" size:9] forKey: NSFontAttributeName];

     CGSize cell_size = [string boundingRectWithSize:CGSizeMake(300,999) 
                            options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin     
                            attributes:stringAttributes context:nil].size;
if (cell_size.height > 70)
{
return cell_size.height;
}
else 
{
return 70;
}
}

EDIT : THIS has been updated for iOS 7

like image 37
Tony Avatar answered Sep 19 '22 20:09

Tony