0

I would like to get the cell frame at tableView:cellForRowAtIndexPath: in order to position and size the views that I want to add to UITableViewCell's contentView. But there self.frame is always (0, 0, 320, 44).

I know you can get the right frame in layoutSubviews (thanks to this answer), but if I add the subviews there it would be done every time the cell is reused, not only once like in the "official" example at Programmatically Adding Subviews to a Cell’s Content View.

In that example they add some views using hardcoded frames like:

mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)];

I guess that example is outdated, since they should use constraints, or at least calculate the size of subviews using the actual cell frame (which may be impossible to get at that point indeed).

Note: this reminds me of the view holder design pattern used in Android.

Community
  • 1
  • 1
Ferran Maylinch
  • 10,919
  • 16
  • 85
  • 100

2 Answers2

0

This should return the bounding frame.

CGRect cellFrame = cell.bounds;

Then you can use it like

cellFrame.size.width;
cellFrame.size.height;
cellFrame.origin.x;
cellFrame.origin.y;

etc... Though origin.x and origin.y should be 0 each.

Maybe you should calculate cell height in a UITableViewCell subclass and use

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

in your delegate to find the correct height.

  • It doesn't work because that rect is by default (0, 0, 320, 44). At layoutSubviews you do get the right bounds. But then the example code in apple docs is useless because you can't pre-build the views in the init method. – Ferran Maylinch Jun 01 '15 at 17:41
0

I use two solutions:

1) When I set the frames explicitly

I fake the frame:

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)

// Use whatever height you like for your cell
// Should be the same value you return in tableView:heightForRowAtIndexPath:
CGFloat cellHeight = XXX;

CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, cellHeight);

 2) When I use autolayout

I just add my views and constraints to self.contentView.

[someView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.contentView addSubview:someView];
[self.contentView addConstraints:someConstraints];

But check this answer just in case.

Community
  • 1
  • 1
Ferran Maylinch
  • 10,919
  • 16
  • 85
  • 100