質問

I have a UITableView for which I created two different custom cells, let's call one "RegularCell" and the other "BigCell". The reason to do so is that I need different representation for the data model objects, where in a certain case I wish to present the data differently.

I read a bit about ways to approach it via heightForRowAtIndexPath vs. cellForRowAtIndexPath, but I'm not clear how to approach it in my case >> In my table, I don't know, in advance, which row will include which custom cell; I only get this data in cellForRowAtIndexPath where I check in the data array which case I need to represent for a specific row.

It seems silly to do the calculation in heightForRowAtIndexPath since it's called before cellForRowAtIndexPath and the whole idea there is that you don't create all the cells in advance and just "make room" for things like the scroller size.

On the other hand, only when I realise which content I'm representing, I can tell which cell I require and therefore what should be the row height.

Anyone encountered a case like that and can share some wisdom?

役に立ちましたか?

解決

David is right!

I don't agree with you saying

In my table, I don't know, in advance, which row will include which custom cell; I only get this data in cellForRowAtIndexPath where I check in the data array which case I need to represent for a specific row.

in heightForRowAtIndexPath you can access you datasource the same way you do it in cellForRowAtIndexPath:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   CGFloat bigCellHeight = 80.0;
   CGFloar regularCellHeight = 44.0;
   MyDataObject *object = [myArray objectAtIndex: indexPath.row];
   if ([object anyConditionToChoseBigCell]) {
      return bigCellHeight;
   }
   return regularCellHeight;
}

他のヒント

heightForRowAtIndexPath is called before cellForRowAtIndexPath as the tableView layouter needs to know how big the scroll view is going to be as well as what cells should be visible on screen at the time its going to be displayed, this may vary depending on the height of each cell.

I've come across this problem before and my recommendation is that you calculate the height of each of the cells in your model before your tableView is even run.

I've had similar problem. That's what I ended up with:

-(CGFloat)tableView:(UITableView *)tableView 
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}

OK... I found an easy solution - Since I have an array of data objects, I can check per each row, the relevant data object relevant property >> in my case, I have a BOOL value called isSuper >> and in this way I can set the row height per each object in the DB without the need to create or upload an actual UITableViewCell in heightForRowAtIndexPath.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top