Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a UITableView row height to auto-size to the size of the UITableViewCell?

Tags:

How to get a UITableView row height to auto-size to the size of the UITableViewCell?

So assuming I'm creating the UITableViewCell in Interface Builder, and it height is more than the standard size, how can I get the UITableView row height to autosize to it? (i.e. as opposed to manually having to measure the height in interface builder and than programmatically setting it)

like image 986
Greg Avatar asked Mar 01 '11 23:03

Greg


People also ask

How do you set the dynamic height of a table view cell?

To get dynamic cell heights working properly, you need to create a custom table view cell and set it up with the right Auto Layout constraints. In the project navigator, select the Views group and press Command-N to create a new file in this group.

How do I create a dynamic height tableView cell in Swift?

Basic Swift Code for iOS Apps To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property. We'll see this with the help of an sample project.

What is Table View delegate?

func tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath) Tells the delegate the table view is about to draw a cell for a particular row. func tableView(UITableView, indentationLevelForRowAt: IndexPath) -> Int. Asks the delegate to return the level of indentation for a row in a given section.

How will you know the end of loading of UITableView?

willDisplayCell: used here for smoother UI (single cell usually displays fast after willDisplay: call). You could also try it with tableView:didEndDisplayingCell: . Much better for knowing when all the cells load that are visible. However this will be called whenever the user scrolls to view more cells.


1 Answers

http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/ is a great tutorial for this.

The main bit is

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; {   // Get the text so we can measure it   NSString *text = [items objectAtIndex:[indexPath row]];   // Get a CGSize for the width and, effectively, unlimited height   CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);   // Get the size of the text given the CGSize we just made as a constraint   CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];   // Get the height of our measurement, with a minimum of 44 (standard cell size)   CGFloat height = MAX(size.height, 44.0f);   // return the height, with a bit of extra padding in   return height + (CELL_CONTENT_MARGIN * 2); } 
like image 173
Brian Avatar answered Oct 06 '22 00:10

Brian