8

Please help me to ask this question. I tried all the choices that I could find here.

The sample of my code is attached (I know, it's pretty bad).
How can I change UITableView height dynamically?

- (void)viewDidLoad 
{
    [super viewDidLoad];
    [self vozvratmassiva];
}

- (NSMutableArray *) vozvratmassiva
{
 ...
    return array;
}

-(NSInteger)numberOfSectionInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *a = [self vozvratmassiva];
    return a.count;
}

-(UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ....
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{
     ....
    return commonsize;
}

@end
Vlad Z.
  • 3,401
  • 3
  • 32
  • 60
serg1991
  • 87
  • 1
  • 1
  • 8

2 Answers2

3

I understand what you're trying to do. Here is what you should do:

  1. Add height constraint to your UITableView
  2. Wrap it in custom UIView
  3. Make a custom class MyCustomView:UIView
  4. Set class in IB for your wraper UIView to your class from step 3.
  5. Make connection from constraint in IB to your class
  6. Make a connection between table view and your class
  7. Put code into your new class:
- (void) layoutSubviews {
  // set height 0, will calculate it later
  self.constraint.constant = 0;

  // force a table to redraw
  [self.tableView setNeedsLayout];
  [self.tableView layoutIfNeeded];

  // now table has real height
  self.constraint.constant = self.tableView.contentSize.height;
}
Nikita Took
  • 3,980
  • 25
  • 33
-3

To change the cell height:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
return commonsize;
}

To change tableView height:

tableView.size.height = 100;
xoail
  • 2,978
  • 5
  • 36
  • 70
  • how can I sum all the heights of cells in this tableview? – serg1991 Feb 26 '14 at 21:21
  • cellheight * number of cells? – xoail Feb 26 '14 at 21:22
  • no, my cells have different heights – serg1991 Feb 26 '14 at 21:22
  • well you can loop through each cell in uitableview and add them up. But that sounds like a bad UI. Just to confirm are you sure you want to keep table's height dynamic? What if there are 100 elements? Besides TableView consists of scroll view which will auto scroll if content goes beyond specified height. Also look at this answer http://stackoverflow.com/questions/14223931/change-uitableview-height-dynamically – xoail Feb 26 '14 at 21:26
  • 1
    questions was about tableview and not Cell , please edit answer accordingly – vishal dharankar Jun 14 '14 at 11:29
  • tableView.size.height not exist. It should be tableView.frame.size.height – Saurabh Shukla Nov 13 '14 at 13:38