One method is to instantiate cell prototypes and calculate their dynamic height based on the data. This method allows you to rely on the storyboard layout (if you use storyboards) without having to hardcode the configuration information of your cell in the view controller.
EDIT I added a working example of cells with dynamic height labels using TLIndexPathTools , which automatically calculates dynamic heights for you if your cell implements the TLDynamicHeightView protocol. See Dynamic Height project. The height calculation is performed in the cell as follows:
@interface DynamicHeightCell () @property (nonatomic) CGSize originalSize; @property (nonatomic) CGSize originalLabelSize; @end @implementation DynamicHeightCell - (void)awakeFromNib { [super awakeFromNib]; self.originalSize = self.bounds.size; self.originalLabelSize = self.label.bounds.size; } - (void)configureWithText:(NSString *)text { self.label.text = text; [self.label sizeToFit]; }
In essence, you remember the original dimensions when the cell wakes up from the storyboard. Then, when the calculation is done, call sizeToFit on the label and use the new size to calculate the height delta and add it to the original height. In the storyboard, you need to set the label width to the desired width and set the number lines to 0.
On the view controller side, if you are using TLIndexPathTools , you just need to customize the data model with an array of strings and set the label on the cells. Prototype and size calculations are performed automatically by the TLTableViewController base class. If you do not want to use TLIndexPathTools , you must draw the bits from the TLTableViewController .
@implementation DynamicHeightTableViewController - (void)viewDidLoad { [super viewDidLoad]; self.indexPathController.items = @[ @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.", @"Fusce ac erat at lectus pulvinar porttitor vitae in mauris. Nam non eleifend tortor.", @"Quisque tincidunt rhoncus pellentesque.", @"Duis mauris nunc, fringilla nec elementum nec, lacinia at turpis. Duis mauris nunc, fringilla nec elementum nec, lacinia at turpis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.", ]; } - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { NSString *item = [self.indexPathController.dataModel itemAtIndexPath:indexPath]; DynamicHeightCell *dynamicCell = (DynamicHeightCell *)cell; [dynamicCell configureWithText:item]; }
source share