动态改变iOS7中UITableView的高度

8

请帮我问这个问题。我已经尝试了所有在这里能找到的选项。

我的代码示例附在下面(我知道,它很糟糕)。
如何动态地更改 UITableView 的高度?

- (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

你想动态地改变tableView的高度还是cell的高度? - Sandeep
我想改变tableView的常规大小。我已经改变了单元格的高度。 - serg1991
我认为这个答案更适合您的要求https://dev59.com/KnbZa4cB1Zd3GeqPJ87c#18784825 - chintan adatiya
@chintanadatiya 哦哦哦!你太棒了!谢谢!现在它可以工作了! - serg1991
2个回答

3
我了解您想做什么。以下是您应该采取的措施:
  1. 为您的UITableView添加高度约束
  2. 将其包装在自定义UIView中
  3. 创建一个自定义类MyCustomView:UIView
  4. 在IB中为您的包装UIView设置类,将其设置为步骤3中的类。
  5. 在IB中从约束到您的类之间建立连接
  6. 在表视图和您的类之间建立连接
  7. 将代码放入您的新类中:
- (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;
}

你觉得应该将这个答案添加为评论吗? - Saad Chaudhry
Kirill的回答可能会在这个链接中帮助到某些人 -> https://dev59.com/cWMl5IYBdhLWcg3wR1WD - Deepak Thakur

-3

更改单元格高度:

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

更改tableView的高度:

tableView.size.height = 100;

我该如何求出这个TableView中所有单元格的高度总和? - serg1991
单元格高度乘以单元格数量? - xoail
不,我的单元格高度不同。 - serg1991
你可以循环遍历UITableView中的每个单元格并将它们相加。但这听起来像是一个糟糕的用户界面。只是为了确认,您确定要保持表格高度动态吗?如果有100个元素怎么办?此外,TableView由滚动视图组成,如果内容超出指定高度,它将自动滚动。还请参考此答案https://dev59.com/mGYq5IYBdhLWcg3wwDNA - xoail
1
问题是关于TableView而不是Cell,请相应地编辑答案。 - vishal dharankar
tableView.size.height不存在。应该是tableView.frame.size.height。 - Saurabh Shukla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接