0

I have a UITableView and I'd like to change its height programmatically depending on the number of cells contained in it.

Can you help me?

Alex P
  • 12,249
  • 5
  • 51
  • 70
Sara Canducci
  • 6,231
  • 5
  • 19
  • 24
  • What you are trying to do is wrong. UITableView will automatically adjust its content size (the scrolling area) depending on how many cells it contains (depending on the data source). – Eugene May 17 '14 at 10:04
  • You can do that. In your `numberOfRowsInSection` method change the frame size of your UITableView `self.tableView.frame = CGRectMake(x,y,width,height);` – Argent May 17 '14 at 10:08
  • possible duplicate of [Change UITableView height dynamically](http://stackoverflow.com/questions/14223931/change-uitableview-height-dynamically) – Peter O. Jun 29 '15 at 22:59

3 Answers3

1

You can use this code

self.yourTableView.frame = CGRectMake(x,y,width,noOfCell*heightOfOneCell);
souvickcse
  • 7,742
  • 5
  • 37
  • 64
1

You can observe tableView.contentSize changes and bind the value to the frame, keep in mind you might run into memory issues since table view won't recycle cells

Sash Zats
  • 5,376
  • 2
  • 28
  • 42
0

Did you tried sizeToFit or sizeThatFits:?

CGRect tFrame = tableView.frame;
tFrame.size.height = MIN([tableView sizeThatFits: CGSizeMake(tFrame.size.width,
                                                             CGFLOAT_MAX)].height,
                         MaximumTableHieght);
tableView.frame = tFrame;

Or try this (I don't remember which was working for me).

CGRect tFrame = tableView.frame;
tFrame.size.height = MIN(tableView.contentSize.height,
                         MaximumTableHieght);
tableView.frame = tFrame;
Marek R
  • 32,568
  • 6
  • 55
  • 140
  • Hi unfortunately it doesn't work and I don't even know why...I used the code and nothing happens! Basically I have a scrolling view with an UIImageView on the top and a UITableView on the bottom, with some cells and I want the whole thing to scroll together...but obviously to do that I need to see ALL the cells into the tableView...so, I need to resize it depending by its content. Any ideas? – Sara Canducci May 17 '14 at 11:47
  • try edited second version, I just don't remember which one worked well. – Marek R May 17 '14 at 12:02