【问题标题】:Adjust UITableView height dynamically动态调整 UITableView 高度
【发布时间】:2014-04-23 09:51:47
【问题描述】:

如何动态调整UITableView 的高度?假设我有 3 行,每行的高度为 65。当将新行添加到 UITableView 时,我希望它动态调整其高度以适应新行。当一行被删除以缩小时,反之亦然。

【问题讨论】:

  • 你有没有尝试过?
  • 我试过这个:stackoverflow.com/a/14228015/1129959 但它太复杂了,一点也不明显
  • 请出示您的代码。
  • @ŁukaszTomaszewski 不是重复的。单元格高度与表格高度
  • 大家不看完整题就急着回答。

标签: ios iphone uitableview autolayout


【解决方案1】:

编辑:误读

事情取决于(表格单元格行的高度*表格中的行数)作为tableview.frame.size.height。

好吧,我会建议这样的东西..

-(void)correctHeight
{

    //Note : if all cells are having common value
    CGFloat heightOfCell=[table rowHeight];

    CGFloat expectedHeightOfTable=0;
    for (int i=0; i< [table numberOfSections]; i++) {
        //header section
        CGFloat heightOfHeaderView=[table headerViewForSection:i].frame.size.height;
        expectedHeightOfTable = expectedHeightOfTable +heightOfHeaderView;

        //content section
         expectedHeightOfTable = expectedHeightOfTable + heightOfCell*[table numberOfRowsInSection:i];
    }
    [table setFrame:CGRectMake(table.frame.origin.x, table.frame.origin.y, table.frame.size.width,expectedHeightOfTable)];


}

这将考虑标题和每行内容以及所有值的填充。所以不需要添加一些硬编码的值

【讨论】:

  • OP 要求改变 UITableView 的高度
  • 谢谢我试过了,tableview的高度在调试时会发生变化,但视觉上总是一样的高度
  • 那是因为它的 supeview 保持不变
【解决方案2】:

tableview的高度可以通过,

[tableView setFrame:CGRectMake(0,0,width,height)];

但是,例如,如果您将高度设置为 150,并且您使用 tableView:heightForRowAtIndexPath: 将 5 行高度设置为 60px:那么 tableView 将变得可滚动,因为 UITableView 是 UIScrollView 的子类。

【讨论】:

    【解决方案3】:

    正如评论中所说,奇怪的结构,但如果你坚持,那没关系。我建议只使用简单的UITableView

    假设您有IBOutletUITableViewUIScrollView...

    viewWillAppear中添加代码之前,添加:

    float cellHeight = 65.0f;
    int numberOfCells = 3;
    

    - (void)viewWillAppear:animated中,在[super viewWillAppear:animated]之后添加以下内容:

    // remember fill the table with data using UITableViewDataSource's functions first
    // refresh UITableView data
    [tableView reloadData];
    // resize UITableView
    [tableView setFrame:CGRectMake(0, 0, tableView.frame.size.width, cellHeight * numberOfCells)];
    // make UIScrollView the same size as UITableView
    [scrollView setContentSize:tableView.frame.size];
    [scrollView setNeedsDisplay];
    // remember to lock tableView's scrolling, either in code / Interface Builder
    [tableView setScrollEnabled:NO];
    

    UITableViewDelegate的委托方法中:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return numberOfCells;
    }
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
       return cellHeight;
    }
    

    最后,如果您想再次验证是否有任何表格单元格不在视线范围内,您可以使用:

    - (NSArray *)visibleCells
    

    【讨论】:

    • 你错过了页眉高度。
    • 是的,如果标题设置为可见(因为标题在大多数情况下是隐藏的)。真的取决于OP的布局。
    • 谢谢你我试过了,tableview的高度在调试时会发生变化,但视觉上它总是一样的高度
    • 我的错。查阅文档后,代码应该放在viewWillAppear:animated而不是viewDidLoad,以便动态更改表格视图大小