Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UITableView's height

I have created a UITableview with custom UITableViewCell.The UITableViewCell contains UILabels and I have calculated the height of each cell based on the cells height.But how can I get the tableview height?Because based on the tableView's height I need to calculate the height of scrollView I have created a UITableView like this when a button is clicked:

-(IBAction)btnClicked:(id)sender
{
    self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0,150,327,[arr5 count]*205) style:UITableViewStylePlain];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    float fscrview = 150 + self.tableView.frame.size.height + 20;
    testscroll.contentSize=CGSizeMake(320, fscrview);
  }
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  {
  NSString *city1 = city.text;
        UIFont *font = [UIFont fontWithName:@"Helvetica" size:14.0];
        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
        CGSize bounds = [city1 sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
//similarly calculated for all 
   return (CGFloat) cell.bounds.size.height + bounds.height+bounds1.height+bounds2.height+bounds3.height+bounds4.height+bounds5.height;
  }

I am able to get tableViewCells height through this.How do I calculate/set the overall tableView's height after this?

And how to calculate ScrollView's height based on tableView's row/height?

like image 394
Sindhia Avatar asked Jan 02 '13 09:01

Sindhia


1 Answers

You also can use KVO to observer tableview's contentSize property and adjust what you need in other views.

Put it somewhere, e.g. in viewDidLoad:

[self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];

Then implement observer:

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
      if (object == self.tableView) {
        self.scrollViewHeightConstraint.constant = self.tableView.contentSize.height;
      }
      else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
      }
    }
like image 159
Vlad E. Borovtsov Avatar answered Oct 29 '22 10:10

Vlad E. Borovtsov