-1

I have used the following code to dynamically change the row height in ios. But the height is too high. I dont know where i made mistake. My code is as follows:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

if(!self.customCell){
    self.customCell = [self.goalDetailsTableview dequeueReusableCellWithIdentifier:@"GoalDetailsCell"];
}

NSMutableDictionary *cellData = [self.databaseCall transactionFromDatabase:indexPath.row goalId:self.goalId andStageId:self.stageId];
//Cell Layout
self.customCell.tipsDescription.text = [cellData objectForKey:@"tipsDescription"];
[self.customCell.tipsDescription sizeToFit];
//Height of cell
float height = (CGRectGetMaxY(self.customCell.tipsDescription.frame) + 20);

return height;
}

Note: tipsDescription is a UILabel inside the UIView which is kept inside the UITableViewCell.

Balaji Kondalrayal
  • 1,743
  • 3
  • 19
  • 38

2 Answers2

0

With iOS 8 we have self sizing table view cells. With it, there is no need to even implement heightForAtIndexPath.

Step 1) Set up constraints for your table cell

Step 2) In viewDidLoad:

self.tableView.estimatedRowHeight = 100.0; //or whatever value you need
self.tableView.rowHeight = UITableViewAutomaticDimension;

And that's it. I would also mention a few of us have ran into an issue where you might need to reload the table view's data in viewDidAppear.

Dreaming In Binary
  • 1,197
  • 6
  • 8
0

You need to calculate your text height and based on it have to set cell height (yes, its going to be little mind expensive but at last you'll be happy!). Here's the one solution for this, Replacement for deprecated sizeWithFont: in iOS 7? and if you want some more info, Calculating number of lines of dynamic UILabel (iOS7) and this too UITableViewCell with UITextView height in iOS 7? (I know its not for UITextView but you can consider it with UILabel).

Community
  • 1
  • 1
Hemang
  • 26,840
  • 19
  • 119
  • 186
  • I have a view inside the tableviewcell, within that view i have a label. So, if i calculate the height of label inside the view, it gives the label height much greater than the expected. CGRectGetMaxY(self.customCell.tipsDescription.frame) + 20, if "CGRectGetMaxY(self.customCell.tipsDescription.frame)" returns value as 30 and adding 20 will return the height as 800 something. Don't know what goes wrong. – Balaji Kondalrayal Dec 03 '14 at 14:03
  • **Your comments don't sounds good, I'm afraid** if you've a view inside cell, then you'll really need to set first height of that view, and based on that calculate height of label. You'll need to perform several tests for this. I can't help you more with this but I'm here you can ask me in comments. One suggestion, if you've only single label inside that view, then don't need to add any view, you can simply add label as subview for `cell.contentView`. Highly recommended ! – Hemang Dec 03 '14 at 14:06