Question

I have a tableview that displays a feed of statuses(pictured below) and im trying to figure out how to size each cell appropriately aka short statuses having a smaller cell and bigger cells that display all the status text for longer statuses. Ive come across this tut: http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/

but, im still a little confused on how I would go about calculating in the extra space for my buttons or the margin to the left for my thumb img.

currently it consists of 2 buttons, a label (for the users name) , a thumb img and a textfield (unsure if I should be using a textfield or label for displaying the status, either or is fine with me if i it works)

Please excuse me in advance if this is a question that has already been answered somewhere. I am primarly a Android developer just getting started in IOS and have found alot of mixed answers on this topic so im a little unsure if there is a simple solution to this problem in IOS7

enter image description here

Was it helpful?

Solution

There are several ways of doing this, but I've found that the most reliable is to use a temporary and invisible UITextView to get the necessary size.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Ideally you should do lazy loading so that instead of creating a new textView each time, you just reuse the same one.
    UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)]; //This initial size doesn't matter
    temp.font = __Your_desired_font__
    temp.text = @"Put your status here";

    CGFloat textViewWidth = __your_constraint_width__
    CGRect tempFrame = CGRectMake(0,0,textViewWidth,44); //The height of this frame doesn't matter.
    CGSize tvsize = [temp sizeThatFits:CGSizeMake(tempFrame.size.width, tempFrame.size.height)]; //This calculates the necessary size so that all the text fits in the necessary width.

    //Add the height of the other UI elements inside your cell

    return tvsize.height + staticElementHeights


}

This works on iOS 7, but I think if you want to support iOS 6 you need to actually add the textView as a subview for this to work. Just set temp.hidden = YES

The way text is displayed in a UILabel is different from a UITextView, so for a UILabel, you should use the method described in this answer iOS auto adjust label height

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top