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)
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.
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With