Setting custom UITableViewCells height
Your UITableViewDelegate
should implement tableView:heightForRowAtIndexPath:
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return [indexPath row] * 20;}
Swift 5
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return indexPath.row * 20}
You will probably want to use NSString
's sizeWithFont:constrainedToSize:lineBreakMode:
method to calculate your row height rather than just performing some silly math on the indexPath :)
If all your rows are the same height, just set the rowHeight
property of the UITableView rather than implementing the heightForRowAtIndexPath
. Apple Docs:
There are performance implications to using tableView:heightForRowAtIndexPath: instead of rowHeight. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).
in a custom UITableViewCell -controller add this
-(void)layoutSubviews { CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height); CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height); self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame; self.frame = newCellViewFrame; [super layoutSubviews];}
In the UITableView -controller add this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return [indexPath row] * 1.5; // your dynamic height...}