3

I'd like to make a custom UITableViewCell height using (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath.

I'm trying to get the height of the UITableViewCell by multiplying the number of lines in textLabel by the height of each line and then adding 10.0f for the subtitle. I am using the following code and getting exc_bad_access(). Why?

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ([[[tableView cellForRowAtIndexPath:indexPath] textLabel] numberOfLines] * [[[[tableView cellForRowAtIndexPath:indexPath] textLabel] font] lineHeight]) + 10.0;
    //return kRowHeightiPod; //A constant value for a sanity check
}
Moshe
  • 55,729
  • 73
  • 263
  • 420
  • take a look at this question. if you look at the second part of the answer, I believe you will find the solution http://stackoverflow.com/questions/129502/how-do-i-wrap-text-in-a-uitableviewcell-without-a-custom-cell – Aaron Saunders Oct 04 '10 at 22:17
  • @Aaron - I believe that it should be simpler. I should not have to redefine a rect for my cell. I should be able to simply calculate the height based on the number of number of lines. I'm trying to get float values for my line height and number of line values. – Moshe Oct 04 '10 at 22:19
  • i think in the end, that solution will prove to be the easiest, you dont have a cell rect yet. – Aaron Saunders Oct 04 '10 at 22:45

2 Answers2

4

Before you can get the cell, you need to compute it's height. You've just made computing it's height dependent on getting the cell. You've created an infinite recursion.

You're going to need to find another way to do your calculation, probably by examining the data you're adding to the table cell, rather than querying the table cell directly.

Also, note that numberOfLines represents the number of lines a text label is capable of displaying, but it may display less if there's not enough content. In other words, even if it's only displaying one line of text, numberOfLines will return two if that's the maximum number of lines the text label is capable of displaying.

What you probably want is to use one of the NSString UIKit additions to compute the height of text text you want to display in the cell.

Kris Markel
  • 12,072
  • 3
  • 40
  • 40
0

Do you set number of lines on the label? Because that's going to give you an answer that is the default, not the number of lines that match the text you are using...

I'd say the most likely cause of a crash is something to do with the textLabel. Try setting NSZombieEnabled to YES in the environment variables for the executable, and the log will tell you what kind of object is being called after it is released...

Kendall Helmstetter Gelner
  • 73,251
  • 26
  • 123
  • 148