如何在 UITableViewController 中设置静态单元格的自动高度?

How to set automatic height of static cell in UITableViewController?

我正在使用 IB 和故事板,并且我定义了 UITableViewController。我在那里定义了三个 static 单元格。前两个应该有一个给定的高度,但最后一个应该自动填充剩余的 space(锚点到视图的底部)。我怎样才能做到这一点?我可以为单元格 内部 的控件使用自动布局,但单元格本身显示为灰色。

最好的解决方案是从 IB 执行此操作,但也欢迎程序化解决方案。

编辑:

这是它在我的故事板中的样子(颜色用于可视化单独的控件,每个控件都有所需的约束):

启动后: 请注意,文本视图在屏幕底部下方结束。

我忘了说我的目标是 iOS 7.0+。

IB 不确定并使用自动布局

但以编程方式使用,

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

使用此方法您可以检查 indexpath.row。并使用这个 return 不同的高度。

对于静态(非数据驱动)高度,您可以将单元格出列一次并存储高度:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSNumber *height;
    if (!height) {
        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MyCustomCell"];
        height = @(cell.bounds.size.height);
    }
    return [height floatValue];
}

我在博客 post 中使用静态 table 视图和使用自动布局设置单元格高度对此进行了介绍。单元格都在界面生成器中定义。

您必须在代码中启用自动单元格高度,但这只是几行。

我展示了一切,包括IB和代码。

看看

http://www.oliverfoggin.com/using-a-static-uitableview-as-a-layout-device/

好的,试试这个

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{

    if indexPath.row == 0 { 
        return firstRowHeight
    }
    else if indexPath.row == 1 { 
        return secondRowHeight 
    }
    else { 
        return tableView.frame.size.height - firstRowHeight - secondRowHeight 
    }
}

唯一可能有问题的是,此方法将在视图设置 tableView 高度

之前运行

您实际上可以将 UITableViewAutomaticDimension 用于静态单元格。按照惯例设计静态单元格,并通过添加

手动将单元格设置为动态高度
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 240 // Something reasonable to help ios render your cells

现在覆盖 heightForRow 委托

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return UITableView.automaticDimension
}

我注意到此技术的唯一其他警告是您必须使用 NSAutolayout 来创建对底部容器(UITableViewCell 的容器)的约束。因此,假设您在单元格的 contentView 中有一个容器,该容器将具有动态高度,要使其正确呈现,您需要创建底部 space 约束。

如果您有一些具有固定高度的静态单元格,我建议通过在 tableView:heightForRowAtIndexPath:indexPath

中打开行来返回该尺寸

一定要覆盖 heightForRowAtIndexPath!否则根据我的经验它不会正确显示

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{
    return UITableViewAutomaticDimension
} 

如果整个 tableview 单元格高度是动态的那么你可以试试这个

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 240

或者 tableview 需要一些固定高度的单元格和一些动态高度的单元格,你可以查看答案

希望对您有所帮助。

Ryan Romanchuk 的回答很棒。我有一个小窍门可以帮助像我这样的初学者。

由于这是一个静态单元格案例,您可能倾向于对每个动态字段使用 IBOutlet。在 tableView 负载周期之外设置 UILabel 中的值将不会考虑新的高度。

要允许动态高度起作用,您可以在重写的 cellForRowAtIndexPath 委托中分配值,以便自动布局可以选择新的高度。当您想要更新字段时调用 tableView.reloadData()